Create file
To create an empty file in Node.js:
const fs = require('node:fs/promises');
const filename = 'file.txt';
let fh = await fs.open(filename, 'a');
await fh.close();
Here, a (blank) file is written with fs.open and then closed with fh.close.
touch file
To touch
a file, however, requires a bit more work (credit boutell):
const fs = require('node:fs/promises');
const filename = 'file.txt';
const time = new Date();
await fs.utimes(filename, time, time).catch(async function (err) {
if ('ENOENT' !== err.code) {
throw err;
}
let fh = await fs.open(filename, 'a');
await fh.close();
});
fs.utimes 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.
Blocking
To do this synchronously, we can use the legacy blocking methods fs.closeSync, fs.openSync, fs.utimesSync:
const fs = require('node:fs');
const filename = 'file.txt';
const time = new Date();
try {
fs.utimesSync(filename, time, time);
} catch (e) {
let fd = fs.openSync(filename, 'a');
fs.closeSync(fd);
}
Examples
You can find a list of approaches in the Gist below: