How to generate unique temporary file names in Node

By: ( +David Herron; Date: 2013-12-17 16:35

Tags: Node.JS

Often we want to write data to a file, don't really care what the file name is, but want to be sure our code is the only code accessing that data.  A trivial algorithm might be to form a file name like:


The process ID is unique to our process, and a simple counter is some assurance that two pieces of code won't step on each others temporary files.  But what about a security vulnerability from untrusted nefarious code?  This file name pattern is very predictable, and nefarious code could subvert the good code with bad data.

In one of my ( AkashaCMS plugins I needed to create temporary files and after some searching chose to use the temporary module.

Its usage is straight-forward:

var tmp = require('temporary');
var file = new tmp.File();
var dir = new tmp.Dir();
console.log(file.path); // path.
console.log(dir.path); // path.

In other words, if you need a new temporary file or directory just instantiate a new object, do stuff with it, then delete it when done.

Another module, (, does a bit more.  It tracks the files and directories created, so you can clean them up when done.  It also integrates with Grunt so it can be used in building things.

Another module, (, is closer to the module I chose for AkashaCMS.

« Node.js is a big win at PayPal MacOS X setup for Node.js development - Installing Node »