[英]Update the "last modified date" of a file
我想將文件的最后修改日期設置為當前日期以避免包裹緩存(不幸的是我沒有找到更好的方法)。
所以我寫道:
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 所做的一致。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.