fsPromises.watch(filename[, options])
filename
<string> | <Buffer> | <URL>options
<string> | <Object>persistent
<boolean> 指示只要正在监视文件,进程是否应继续运行。 默认值:true
。recursive
<boolean> 指示是应监视所有子目录,还是仅监视当前目录。 这在指定目录时适用,并且仅在受支持的平台上有效(请参见注意事项)。 默认值:false
。encoding
<string> 指定用于传给监听器的文件名的字符编码。 默认值:'utf8'
。signal
<AbortSignal> 用于指示监视器何时应停止的 <AbortSignal>。
- 返回: <AsyncIterator> 具有以下属性的对象:
返回异步迭代器,其监视 filename
上的更改,其中 filename
是文件或目录。
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'
。
fs.watch()
的所有注意事项也适用于 fsPromises.watch()
。
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> An <AbortSignal> used to signal when the watcher should stop.
- Returns: <AsyncIterator> of objects with the properties:
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;
}
})();
On most platforms, 'rename'
is emitted whenever a filename appears or
disappears in the directory.
All the caveats for fs.watch()
also apply to fsPromises.watch()
.