How to touch a file in Node.js


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:

// callback
const { close, open, utimes } = require('fs');
const touch = (path, callback) => {
const time = new Date();
utimes(path, time, time, err => {
if (err) {
return open(path, 'w', (err, fd) => {
err ? callback(err) : close(fd, callback);
});
}
callback();
});
};
// usage
const filename = 'file.txt';
touch(filename, err => {
if (err) throw err;
console.log(`touch ${filename}`);
});
// promise
const { close, open, utimes } = require('fs');
const touch = path => {
return new Promise((resolve, reject) => {
const time = new Date();
utimes(path, time, time, err => {
if (err) {
return open(path, 'w', (err, fd) => {
if (err) return reject(err);
close(fd, err => (err ? reject(err) : resolve(fd)));
});
}
resolve();
});
});
};
// usage
const filename = 'file.txt';
touch(filename)
.then(fd => console.log(`touch ${filename}`))
.catch(err => {
throw err;
});
// sync
const { closeSync, openSync, utimesSync } = require('fs');
const touch = path => {
const time = new Date();
try {
utimesSync(path, time, time);
} catch (err) {
closeSync(openSync(path, 'w'));
}
}
// usage
const filename = 'file.txt';
touch(filename);
console.log(`touch ${filename}`);
view raw touch-sync.js hosted with ❤ by GitHub


Please support this site and join our Discord!