How to generate unique temporary file names in Node

; Date: Tue Dec 17 2013

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:

/tmp/tf(PID)(Count)

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 (github.com) 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.
file.unlink();
dir.rmdir();

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, (github.com) https://github.com/bruce/node-temp, 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, (npmjs.org) https://npmjs.org/package/tmp, is closer to the module I chose for AkashaCMS.

About the Author(s)

(davidherron.com) David Herron : David Herron is a writer and software engineer focusing on the wise use of technology. He is especially interested in clean energy technologies like solar power, wind power, and electric cars. David worked for nearly 30 years in Silicon Valley on software ranging from electronic mail systems, to video streaming, to the Java programming language, and has published several books on Node.js programming and electric vehicles.

Books by David Herron

(Sponsored)