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


监视 filename 的变化。 每次访问文件时都会调用回调 listener

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

listener 具有两个参数,当前的统计对象和上一个统计对象:

import { watchFile } from 'node:fs';

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

这些统计对象是 fs.Stat 的实例。 如果 bigint 选项为 true,则这些对象中的数值被指定为 BigInt

要在文件被修改(而不仅仅是访问)时得到通知,则需要比较 curr.mtimeMsprev.mtimeMs

fs.watchFile 操作导致 ENOENT 错误时,它将调用监听器一次,且所有字段均清零(或者,对于日期,则为 Unix Epoch)。 如果文件是后来创建的,则将使用最新的统计对象再次调用监听器。 这是自 v0.10 以来的功能变化。

使用 fs.watch()fs.watchFilefs.unwatchFile 更高效。 应尽可能使用 fs.watch 而不是 fs.watchFilefs.unwatchFile

fs.watchFile() 正在监视的文件消失并重新出现时,则第二个回调事件(文件的重新出现)中的 previous 的内容将与第一个回调事件(文件的消失)中的 previous 的内容相同。

这发生在:

  • 文件被删除,然后恢复
  • 文件被重命名,然后再次重命名回其原始名称

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:

import { watchFile } from 'node: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. If the bigint option is true, the numeric values in these objects are specified as BigInts.

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

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). 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 contents of previous in the second callback event (the file's reappearance) will be the same as the contents of previous in the first callback event (its disappearance).

This happens when:

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