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


监视 filename 的变化,其中 filename 是文件或目录。

第二个参数是可选的。 如果 options 作为字符串提供,则它指定 encoding。 否则 options 应作为对象传入。

监听器回调有两个参数 (eventType, filename)eventType'rename''change'filename 是触发事件的文件的名称。

在大多数平台上,只要目录中文件名出现或消失,就会触发 'rename'

监听器回调绑定到由 <fs.FSWatcher> 触发的 'change' 事件,但它与 eventType'change' 值不同。

如果传入了 signal,则中止相应的 AbortController 将关闭返回的 <fs.FSWatcher>

  • filename <string> | <Buffer> | <URL>
  • options <string> | <Object>
    • persistent <boolean> Indicates whether the process should continue to run as long as files are being watched. Default: true.
    • recursive <boolean> Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See caveats). Default: false.
    • encoding <string> Specifies the character encoding to be used for the filename passed to the listener. Default: 'utf8'.
    • signal <AbortSignal> allows closing the watcher with an AbortSignal.
  • listener <Function> | <undefined> Default: undefined
  • Returns: <fs.FSWatcher>

Watch for changes on filename, where filename is either a file or a directory.

The second argument is optional. If options is provided as a string, it specifies the encoding. Otherwise options should be passed as an object.

The listener callback gets two arguments (eventType, filename). eventType is either 'rename' or 'change', and filename is the name of the file which triggered the event.

On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.

The listener callback is attached to the 'change' event fired by <fs.FSWatcher>, but it is not the same thing as the 'change' value of eventType.

If a signal is passed, aborting the corresponding AbortController will close the returned <fs.FSWatcher>.