From ef6af8ccd853aa0cf61db5e961c41bc3e1b17ace Mon Sep 17 00:00:00 2001 From: Benjamin Gruenbaum Date: Tue, 2 Feb 2021 19:30:43 +0200 Subject: [PATCH] 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 Reviewed-By: Antoine du Hamel Reviewed-By: Darshan Sen --- doc/api/fs.md | 7 +++++ lib/fs.js | 11 +++++++ test/parallel/test-fs-watch-abort-signal.js | 32 +++++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 test/parallel/test-fs-watch-abort-signal.js diff --git a/doc/api/fs.md b/doc/api/fs.md index 35a0fd462bc652..edb6656fad2c41 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -4060,6 +4060,9 @@ this API: [`fs.utimes()`][]. diff --git a/lib/fs.js b/lib/fs.js index 49dbe2cb621e71..8d27c5b2d9279c 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1571,6 +1571,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; } diff --git a/test/parallel/test-fs-watch-abort-signal.js b/test/parallel/test-fs-watch-abort-signal.js new file mode 100644 index 00000000000000..e5589bc1140f8b --- /dev/null +++ b/test/parallel/test-fs-watch-abort-signal.js @@ -0,0 +1,32 @@ +// Flags: --expose-internals --experimental-abortcontroller +'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()); +}