How to touch a file in Node.js


To synchronously touch (or create an empty) a file in Node.js:

const fs = require('fs');
const filename = 'file.txt';
fs.closeSync(fs.openSync(filename, 'w'));

But what if we don’t want to block the event loop? We could convert it to the asynchronous callback style:

// ...
fs.open(filename, 'w', (err, fd) => {
  if (err) throw err;
  fs.close(fd, err => { if (err) throw err; });
});

And for those who prefer the promise syntax:

// ...
const { promisify } = require('util');
const open = promisify(fs.open);
const close = promisify(fs.close);
open(filename, 'w').then(close);

promisify is available in Node.js 8+.

You can find a list of approaches below: