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


  • filename <string> | <Buffer> | <URL>

  • options <string> | <Object>

    • persistent <boolean> 指示只要正在监视文件,进程是否应继续运行。默认值:true

      ¥persistent <boolean> Indicates whether the process should continue to run as long as files are being watched. Default: true.

    • recursive <boolean> 指示是应监视所有子目录,还是仅监视当前目录。这在指定目录时适用,并且仅适用于受支持的平台(参见 caveats)。默认值:false

      ¥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> 指定用于传给监听器的文件名的字符编码。默认值:'utf8'

      ¥encoding <string> Specifies the character encoding to be used for the filename passed to the listener. Default: 'utf8'.

    • signal <AbortSignal> 允许使用 AbortSignal 关闭监视器。

      ¥signal <AbortSignal> allows closing the watcher with an AbortSignal.

  • listener <Function> | <undefined> 默认值:undefined

    ¥listener <Function> | <undefined> Default: undefined

  • 返回:<fs.FSWatcher>

    ¥Returns: <fs.FSWatcher>

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

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

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

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

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

¥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.

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

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

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

¥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.

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

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