fs.watchFile(filename[, options], listener)


监视 filename 的更改。 每当访问文件时都会调用 listener 回调。

options 参数可以省略。 如果提供,则它应该是一个对象。 options 对象可以包含一个名为 persistent 的布尔值,指示当文件正在被监视时,进程是否应该继续运行。 options 对象可以指定 interval 属性,指示轮询目标的频率(以毫秒为单位)。

listener 有两个参数,当前的 stat 对象和之前的 stat 对象:

fs.watchFile('message.text', (curr, prev) => {
  console.log(`当前的最近修改时间是: ${curr.mtime}`);
  console.log(`之前的最近修改时间是: ${prev.mtime}`);
});

这些 stat 对象是 fs.Stat 的实例。

要在修改文件(而不仅仅是访问)时收到通知,则需要比较 curr.mtimeprev.mtime

fs.watchFile 操作导致 ENOENT 错误时,它将调用一次监听器,并将所有字段置零(或将日期设为 Unix 纪元)。 在 Windows 中, blksizeblocks 字段会是 undefined 而不是零。 如果文件是在那之后创建的,则监听器会被再次调用,且带上最新的 stat 对象。 这是 v0.10 之后的功能变化。

使用 fs.watch()fs.watchFilefs.unwatchFile 更高效。 应尽可能使用 fs.watch 代替 fs.watchFilefs.unwatchFile

fs.watchFile() 正在监视的文件消失并重新出现时,第二次回调事件(文件重新出现)返回的 previousStat 会与第一次回调事件(文件消失)返回的 previousStat 相同。

这种情况发生在:

  • 文件被删除,然后又恢复。
  • 文件被重命名两次,且第二次重命名回其原来的名称。

Watch for changes on filename. The callback listener will be called each time the file is accessed.

The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates whether the process should continue to run as long as files are being watched. The options object may specify an interval property indicating how often the target should be polled in milliseconds.

The listener gets two arguments the current stat object and the previous stat object:

fs.watchFile('message.text', (curr, prev) => {
  console.log(`the current mtime is: ${curr.mtime}`);
  console.log(`the previous mtime was: ${prev.mtime}`);
});

These stat objects are instances of fs.Stat.

To be notified when the file was modified, not just accessed, it is necessary to compare curr.mtime and prev.mtime.

When an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). In Windows, blksize and blocks fields will be undefined, instead of zero. If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.

Using fs.watch() is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.

When a file being watched by fs.watchFile() disappears and reappears, then the previousStat reported in the second callback event (the file's reappearance) will be the same as the previousStat of the first callback event (its disappearance).

This happens when:

  • the file is deleted, followed by a restore
  • the file is renamed twice - the second time back to its original name