fs: fix recursive watch error handling

Recursive watch inverted the throwIfNoEntry check during setup, causing
the default behavior to suppress ENOENT while the opt-out threw it.
Other setup errors were also silently ignored.

Suppress only ENOENT when throwIfNoEntry is false. Propagate all
other setup failures and close watchers created before a partial
failure.

Signed-off-by: Filip Skokan <panva.ip@gmail.com>
Assisted-by: Codex
PR-URL: https://github.com/nodejs/node/pull/65635
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
This commit is contained in:
Filip Skokan authored and Antoine du Hamel committed 2026-09-19 14:29:36 +02:00
1 parent 33b8d6e10f
commit ba5ca5a1a5
2 files changed
+59 -1

No files matched your search

+2 -1
View File
@@ -234,8 +234,9 @@ class FSWatcher extends EventEmitter {
this.#watchFolder(filename);
}
} catch (error) {
if (!this.#options.throwIfNoEntry && error.code === 'ENOENT') {
if (this.#options.throwIfNoEntry || error.code !== 'ENOENT') {
error.filename = filename;
this.close();
throw error;
}
}
+57
View File
@@ -17,6 +17,8 @@ const {
UV_ENODEV,
UV_ENOENT
} = internalBinding('uv');
const { FSWatcher: RecursiveFSWatcher } = require('internal/fs/recursive_watch');
const { kFSWatchStart } = require('internal/fs/watchers');
tmpdir.refresh();
@@ -66,6 +68,61 @@ tmpdir.refresh();
}
}
{
assert.throws(
() => fs.watch(nonexistentFile, {
recursive: true,
throwIfNoEntry: true,
}, common.mustNotCall()),
{
path: nonexistentFile,
filename: nonexistentFile,
code: 'ENOENT',
},
);
}
{
const watcher = fs.watch(nonexistentFile, {
recursive: true,
throwIfNoEntry: false,
}, common.mustNotCall());
watcher.close();
}
{
const directory = tmpdir.resolve('recursive-watch-error');
const expected = new Error('recursive watcher failed');
const originalWatch = fs.watch;
const watcher = new RecursiveFSWatcher({ recursive: true });
const close = common.mustCall();
let calls = 0;
expected.code = 'ENOSPC';
fs.mkdirSync(directory);
fs.writeFileSync(`${directory}/file`, '');
fs.watch = common.mustCall(() => {
if (calls++ === 0) {
return { close };
}
throw expected;
}, 2);
try {
assert.throws(
() => watcher[kFSWatchStart](directory),
(error) => {
assert.strictEqual(error, expected);
assert.strictEqual(error.filename, directory);
return true;
},
);
} finally {
fs.watch = originalWatch;
watcher.close();
}
}
{
if (common.isMacOS || common.isWindows) {
const file = tmpdir.resolve('file-to-watch');