How to touch a file in Node.js


Create file

To create an empty file in Node.js:

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

Here, a (blank) file is written with fs.openSync and then closed with fs.closeSync.

touch file

To touch a file, however, requires a bit more work (credit boutell):

const fs = require('fs');
const filename = 'file.txt';
const time = new Date();

try {
  fs.utimesSync(filename, time, time);
} catch (err) {
  fs.closeSync(fs.openSync(filename, 'w'));
}

fs.utimesSync is used here to prevent existing file contents from being overwritten.

It also updates the last modification timestamp of the file, which is consistent with what POSIX touch does.

Callback

To do this asynchronously, we can use the non-blocking methods fs.close, fs.open, fs.utimes:

const fs = require('fs');
const filename = 'file.txt';
const time = new Date();

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

Examples

You can find a list of approaches in the Gist below:



If you enjoyed this post, please consider supporting this site!