简体   繁体   中英

fs.watchFile delayed nodejs

If you run the following script I run into the issue that the script doesn't run on every 1sec update but less frequent like every 3-5 seconds. Is this a bug of node.js or is there a way to fix it?

var http = require('http');
var fs = require('fs');
var f = "C:\\Test.txt";
fs.watchFile(f, (curr, prev) => {
  console.log(`the current mtime is: ${curr.mtime} ${prev.mtime}`);
  console.log(String(fs.readFileSync(f)));
});

setInterval(function() {
  fs.writeFileSync('C:\\Test.txt',String(Date.now()));
}, 1000);

It is writing correctly on setInterval but fs.watchFile polls at its own interval. You can set the polling interval with the options parameter:

fs.watchFile(f, {interval: 1000}, (curr, prev) => {
    ...
}

This should work more like you expect.

 fs.watchFile(f, {interval: 2000}, (curr, prev) => { console.log(`the current mtime is: ${curr.mtime} ${prev.mtime}`); console.log(String(fs.readFileSync(f))); }); 

will check file every 2 seconds, default appears to be 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM