更新文件的 "last modified date"

Update the "last modified date" of a file

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

所以我写道:

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所做的一致。