fs: add AbortSignal support to watch

PR-URL: https://github.com/nodejs/node/pull/37190
Refs: https://github.com/nodejs/node/pull/37179
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Darshan Sen <raisinten@gmail.com>
This commit is contained in:
Benjamin Gruenbaum authored and Benjamin Gruenbaum committed 2021-02-05 12:35:57 +02:00
1 parent 6385340774
commit 664cce92ec
3 files changed
+50

No files matched your search

+7
View File
@@ -4133,6 +4133,9 @@ this API: [`fs.utimes()`][].
<!-- YAML
added: v0.5.10
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/37190
description: Added support for closing the watcher with an AbortSignal.
- version: v7.6.0
pr-url: https://github.com/nodejs/node/pull/10739
description: The `filename` parameter can be a WHATWG `URL` object using
@@ -4152,6 +4155,7 @@ changes:
`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`
* `eventType` {string}
* `filename` {string|Buffer}
@@ -4174,6 +4178,9 @@ 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`][].
### Caveats
<!--type=misc-->
+11
View File
@@ -1579,6 +1579,17 @@ function watch(filename, options, listener) {
if (listener) {
watcher.addListener('change', listener);
}
if (options.signal) {
if (options.signal.aborted) {
process.nextTick(() => watcher.close());
} else {
const listener = () => watcher.close();
options.signal.addEventListener('abort', listener);
watcher.once('close', () => {
options.signal.removeEventListener('abort', listener);
});
}
}
return watcher;
}
@@ -0,0 +1,32 @@
// Flags: --expose-internals
'use strict';
// Verify that AbortSignal integration works for fs.watch
const common = require('../common');
if (common.isIBMi)
common.skip('IBMi does not support `fs.watch()`');
const fs = require('fs');
const fixtures = require('../common/fixtures');
{
// Signal aborted after creating the watcher
const file = fixtures.path('empty.js');
const ac = new AbortController();
const { signal } = ac;
const watcher = fs.watch(file, { signal });
watcher.once('close', common.mustCall());
setImmediate(() => ac.abort());
}
{
// Signal aborted before creating the watcher
const file = fixtures.path('empty.js');
const ac = new AbortController();
const { signal } = ac;
ac.abort();
const watcher = fs.watch(file, { signal });
watcher.once('close', common.mustCall());
}