How to create temporary file in Node.js

nodejs_temporary.png

We can use node-tmp as temporary file and directory creator. Tmp offers both an asynchronous and a synchronous API. It's a widely used library in node.js world.

Install

# locally
npm install tmp

# globally
sudo npm install -g tmp
cd ~/projects/projectA
npm link tmp

Asynchronous file creation

var tmp = require('tmp');
var fs = require('fs');

tmp.file(function (err, path, fd, cleanupCallback) {
    if (err) throw err;

    console.log("File: ", path);
    console.log("Filedescriptor: ", fd);
    fs.writeFileSync(path, "Hello world!")
});

Asynchronous file creation with prefix and postfix and keep file

var tmp = require('tmp');
var fs = require('fs');

tmp.file({prefix: 'projectA-', postfix: '.txt', keep: true}, function (err, path, fd, cleanupCallback) {
    if (err) throw err;

    console.log("File: ", path);
    console.log("Filedescriptor: ", fd);
    fs.writeFileSync(path, "Hello world!")
});

Synchronous file creation

var tmp = require('tmp');

var tmpObj = tmp.fileSync({ mode: 0644, prefix: 'projectA-', postfix: '.txt' });
console.log("File: ", tmpObj.name);
console.log("Filedescriptor: ", tmpObj.fd);

Also, you can create temporary directory and generate filename, more here.

comments powered by Disqus