fsPromises.watch(filename[, options])


  • 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> An <AbortSignal> used to signal when the watcher should stop.

  • 返回:<AsyncIterator> 个具有以下属性的对象:

    ¥Returns: <AsyncIterator> of objects with the properties:

返回异步迭代器,其监视 filename 上的更改,其中 filename 是文件或目录。

¥Returns an async iterator that watches for changes on filename, where filename is either a file or a directory.

const { watch } = require('node:fs/promises');

const ac = new AbortController();
const { signal } = ac;
setTimeout(() => ac.abort(), 10000);

(async () => {
  try {
    const watcher = watch(__filename, { signal });
    for await (const event of watcher)
      console.log(event);
  } catch (err) {
    if (err.name === 'AbortError')
      return;
    throw err;
  }
})(); 

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

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

fs.watch() 的所有 caveats 也适用于 fsPromises.watch()

¥All the caveats for fs.watch() also apply to fsPromises.watch().