1

I want to create a temporary file (or directory), similarly to what the Linux mkstemp command does.

With what software can I do that in Node.js?

Requirements:

  • Free
  • Open source
  • Secure randome name, to avoid any symlink race
  • Fast
  • Reasonably small
2

https://github.com/raszi/node-tmp

A simple temporary file and directory creator for node.js.

  • Does just that
  • Free
  • Open source: MIT License
  • Updated 3 months ago
  • Has not reached 1.0

Example usage:

var tmp = require('tmp');

var tmpobj = tmp.dirSync();
console.log("Dir: ", tmpobj.name);

// Manual cleanup
tmpobj.removeCallback();
2

If you use Node.js 5.10.1 or later, there is a native function:

fs.mkdtemp()
  • Does not seem to have any documentation yet
  • Works only for folders
1

https://github.com/bruce/node-temp

Temporary files, directories, and streams for Node.js.

  • Does streams too
  • Automatically track and cleanup files at exit
  • Free
  • Open source: MIT License
  • Updated a year ago
  • Has not reached 1.0

Example usage:

var temp = require('temp'),
    fs   = require('fs'),
    util  = require('util'),
    exec = require('child_process').exec;

// Automatically track and cleanup files at exit
temp.track();

// Fake data
var myData = "foo\nbar\nfoo\nbaz";

// Process the data (note: error handling omitted)
temp.open('myprefix', function(err, info) {
  if (!err) {
    fs.write(info.fd, myData);
    fs.close(info.fd, function(err) {
      exec("grep foo '" + info.path + "' | wc -l", function(err, stdout) {
        util.puts(stdout.trim());
      });
    });
  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.