更新文件的"last modified date"



我想将文件的上次修改日期设置为当前日期以避免包裹缓存(不幸的是我没有找到更好的方法(。

所以我写道:

const fs = require('fs');
const file = 'test.txt';
// save the content of the file
const content = fs.readFileSync(file);
// modify the file
fs.appendFileSync(file, ' ');
// restore the file content
fs.writeFileSync(file, content);

它有效,但唔...
它真的很丑,对于大文件来说非常慢且占用内存。

改编自 https://remarkablemark.org/blog/2017/12/17/touch-file-nodejs/:

const fs = require('fs');
const filename = 'test.txt';
const time = new Date();
try {
fs.utimesSync(filename, time, time);
} catch (err) {
fs.closeSync(fs.openSync(filename, 'w'));
}

此处使用 fs.utimesSync 来防止现有文件内容被覆盖。

它还会更新文件的上次修改时间戳,这与 POSIX touch 的作用一致。

最新更新