fs.watchFile(filename[, options], listener)
filename<string> | <Buffer> | <URL>options<Object>listener<Function>current<fs.Stats>previous<fs.Stats>
- 返回:<fs.StatWatcher>
监视 filename 的更改。每次访问该文件时,回调 listener 都会被调用。
🌐 Watch for changes on filename. The callback listener will be called each
time the file is accessed.
options 参数可以省略。如果提供,它应该是一个对象。options 对象可以包含一个名为 persistent 的布尔值,用于表示只要有文件被监视,进程是否应继续运行。options 对象可以指定一个 interval 属性,用于表示目标应以毫秒为单位的轮询频率。
🌐 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.
listener 接受两个参数:当前的 stat 对象和之前的 stat 对象:
🌐 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}`);
}); 这些 stat 对象是 fs.Stat 的实例。如果 bigint 选项为 true,这些对象中的数值将以 BigInt 形式表示。
🌐 These stat objects are instances of fs.Stat. If the bigint option is true,
the numeric values in these objects are specified as BigInts.
要在文件被修改时收到通知,而不仅仅是被访问,需要比较 curr.mtimeMs 和 prev.mtimeMs。
🌐 To be notified when the file was modified, not just accessed, it is necessary
to compare curr.mtimeMs and prev.mtimeMs.
当 fs.watchFile 操作导致 ENOENT 错误时,它会调用监听器一次,所有字段都为零(或者,对于日期来说,使用 Unix 纪元时间)。如果文件后来被创建,监听器将再次被调用,并提供最新的 stat 对象。这是自 v0.10 以来功能上的变化。
🌐 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.
使用 fs.watch() 比 fs.watchFile 和 fs.unwatchFile 更高效。在可能的情况下,应使用 fs.watch 替代 fs.watchFile 和 fs.unwatchFile。
🌐 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.
当 fs.watchFile() 监视的文件消失又重新出现时,第二次回调事件(文件重新出现)中 previous 的内容将与第一次回调事件(文件消失)中 previous 的内容相同。
🌐 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:
- 文件已被删除,随后恢复
- 文件被重命名,然后再次重命名回原来的名字