From 664cce92ec09363d5a37c9f2a360ee0810fe30e3 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 cac35be697c483..acee67c11ea350 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -4133,6 +4133,9 @@ this API: [`fs.utimes()`][]. diff --git a/lib/fs.js b/lib/fs.js index d01e99c21b0178..368ddfae188fa7 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -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; } 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..cbe9a1457dc9ae --- /dev/null +++ b/test/parallel/test-fs-watch-abort-signal.js @@ -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()); +}