Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -4786,6 +4786,9 @@ The `atime` and `mtime` arguments follow these rules:
<!-- YAML
added: v0.5.10
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/61870
description: Added `throwIfNoEntry` option.
- version: v19.1.0
pr-url: https://github.com/nodejs/node/pull/45098
description: Added recursive support for Linux, AIX and IBMi.
Expand Down Expand Up @@ -4814,6 +4817,8 @@ changes:
* `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.
* `throwIfNoEntry` {boolean} Indicates whether an exception should be thrown when the
path does not exist. **Default:** `true`.
* `ignore` {string|RegExp|Function|Array} Pattern(s) to ignore. Strings are
glob patterns (using [`minimatch`][]), RegExp patterns are tested against
the filename, and functions receive the filename and return `true` to
Expand Down
5 changes: 4 additions & 1 deletion lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -2488,6 +2488,7 @@ function appendFileSync(path, data, options) {
* recursive?: boolean;
* encoding?: string;
* signal?: AbortSignal;
* throwIfNoEntry?: boolean;
* }} [options]
* @param {(
* eventType?: string,
Expand All @@ -2506,6 +2507,7 @@ function watch(filename, options, listener) {

if (options.persistent === undefined) options.persistent = true;
if (options.recursive === undefined) options.recursive = false;
if (options.throwIfNoEntry === undefined) options.throwIfNoEntry = true;

let watcher;
const watchers = require('internal/fs/watchers');
Expand All @@ -2523,7 +2525,8 @@ function watch(filename, options, listener) {
options.persistent,
options.recursive,
options.encoding,
options.ignore);
options.ignore,
options.throwIfNoEntry);
}

if (listener) {
Expand Down
11 changes: 9 additions & 2 deletions lib/internal/fs/recursive_watch.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class FSWatcher extends EventEmitter {
assert(typeof options === 'object');

const { persistent, recursive, signal, encoding, ignore } = options;
let { throwIfNoEntry } = options;

// TODO(anonrig): Add non-recursive support to non-native-watcher for IBMi & AIX support.
if (recursive != null) {
Expand All @@ -66,6 +67,12 @@ class FSWatcher extends EventEmitter {
validateAbortSignal(signal, 'options.signal');
}

if (throwIfNoEntry != null) {
validateBoolean(throwIfNoEntry, 'options.throwIfNoEntry');
} else {
throwIfNoEntry = true;
}
Copy link
Member

@anonrig anonrig Feb 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you just add a default value, which will simplify tracing?

Suggested change
}
} else {
throwIfNoEntry = true;
}


if (encoding != null) {
// This is required since on macOS and Windows it throws ERR_INVALID_ARG_VALUE
if (typeof encoding !== 'string') {
Expand All @@ -76,7 +83,7 @@ class FSWatcher extends EventEmitter {
validateIgnoreOption(ignore, 'options.ignore');
this.#ignoreMatcher = createIgnoreMatcher(ignore);

this.#options = { persistent, recursive, signal, encoding };
this.#options = { persistent, recursive, signal, encoding, throwIfNoEntry };
}

close() {
Expand Down Expand Up @@ -222,7 +229,7 @@ class FSWatcher extends EventEmitter {
this.#watchFolder(filename);
}
} catch (error) {
if (error.code === 'ENOENT') {
if (this.#options.throwIfNoEntry !== false && error.code === 'ENOENT') {
error.filename = filename;
throw error;
}
Expand Down
9 changes: 7 additions & 2 deletions lib/internal/fs/watchers.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const {
} = internalBinding('fs');

const { FSEvent } = internalBinding('fs_event_wrap');
const { UV_ENOSPC } = internalBinding('uv');
const { UV_ENOSPC, UV_ENOENT } = internalBinding('uv');
const { EventEmitter } = require('events');

const {
Expand Down Expand Up @@ -293,7 +293,8 @@ FSWatcher.prototype[kFSWatchStart] = function(filename,
persistent,
recursive,
encoding,
ignore) {
ignore,
throwIfNoEntry = true) {
if (this._handle === null) { // closed
return;
}
Expand All @@ -313,6 +314,10 @@ FSWatcher.prototype[kFSWatchStart] = function(filename,
recursive,
encoding);
if (err) {
if (!throwIfNoEntry && err === UV_ENOENT) {
return;
}

const error = new UVException({
errno: err,
syscall: 'watch',
Expand Down
12 changes: 8 additions & 4 deletions lib/internal/main/watch_mode.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,8 @@ markBootstrapComplete();

const kKillSignal = convertToValidSignal(getOptionValue('--watch-kill-signal'));
const kShouldFilterModules = getOptionValue('--watch-path').length === 0;
const kEnvFiles = [
...getOptionValue('--env-file'),
...getOptionValue('--env-file-if-exists'),
];
const kEnvFiles = getOptionValue('--env-file');
const kOptionalEnvFiles = getOptionValue('--env-file-if-exists');
const kWatchedPaths = ArrayPrototypeMap(getOptionValue('--watch-path'), (path) => resolve(path));
const kPreserveOutput = getOptionValue('--watch-preserve-output');
const kCommand = ArrayPrototypeSlice(process.argv, 1);
Expand Down Expand Up @@ -105,6 +103,10 @@ function start() {
if (kEnvFiles.length > 0) {
ArrayPrototypeForEach(kEnvFiles, (file) => watcher.filterFile(resolve(file)));
}
if (kOptionalEnvFiles.length > 0) {
ArrayPrototypeForEach(kOptionalEnvFiles,
(file) => watcher.filterFile(resolve(file), undefined, { allowMissing: true }));
}
child.once('exit', (code) => {
exited = true;
const waitingForChanges = 'Waiting for file changes before restarting...';
Expand Down Expand Up @@ -160,6 +162,7 @@ async function stop(child) {
}

let restarting = false;

async function restart(child) {
if (restarting) return;
restarting = true;
Expand Down Expand Up @@ -198,5 +201,6 @@ function signalHandler(signal) {
process.exit(exitCode ?? kNoFailure);
};
}

process.on('SIGTERM', signalHandler('SIGTERM'));
process.on('SIGINT', signalHandler('SIGINT'));
12 changes: 7 additions & 5 deletions lib/internal/watch_mode/files_watcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,13 @@ class FilesWatcher extends EventEmitter {
return [...this.#watchers.keys()];
}

watchPath(path, recursive = true) {
watchPath(path, recursive = true, options = kEmptyObject) {
if (this.#isPathWatched(path)) {
return;
}
const watcher = watch(path, { recursive, signal: this.#signal });
const { allowMissing = false } = options;

const watcher = watch(path, { recursive, signal: this.#signal, throwIfNoEntry: !allowMissing });
watcher.on('change', (eventType, fileName) => {
// `fileName` can be `null` if it cannot be determined. See
// https://github.com/nodejs/node/pull/49891#issuecomment-1744673430.
Expand All @@ -126,14 +128,14 @@ class FilesWatcher extends EventEmitter {
}
}

filterFile(file, owner) {
filterFile(file, owner, options = kEmptyObject) {
if (!file) return;
if (supportsRecursiveWatching) {
this.watchPath(dirname(file));
this.watchPath(dirname(file), true, options);
} else {
// Having multiple FSWatcher's seems to be slower
// than a single recursive FSWatcher
this.watchPath(file, false);
this.watchPath(file, false, options);
}
this.#filteredFiles.add(file);
if (owner) {
Expand Down
23 changes: 23 additions & 0 deletions test/parallel/test-fs-watch-enoent.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,29 @@ tmpdir.refresh();
);
}

{
assert.throws(
() => fs.watch(nonexistentFile, { throwIfNoEntry: true }, common.mustNotCall()),
(err) => {
assert.strictEqual(err.path, nonexistentFile);
assert.strictEqual(err.filename, nonexistentFile);
return err.code === 'ENOENT' || err.code === 'ENODEV';
},
);
}

{
if (common.isAIX) {
assert.throws(
() => fs.watch(nonexistentFile, { throwIfNoEntry: false }, common.mustNotCall()),
(err) => err.code === 'ENODEV',
);
} else {
const watcher = fs.watch(nonexistentFile, { throwIfNoEntry: false }, common.mustNotCall());
watcher.close();
}
}

{
if (common.isMacOS || common.isWindows) {
const file = tmpdir.resolve('file-to-watch');
Expand Down
21 changes: 21 additions & 0 deletions test/sequential/test-watch-mode.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,27 @@ describe('watch mode', { concurrency: !process.env.TEST_PARALLEL, timeout: 60_00
}
});

it('should not crash when --env-file-if-exists points to a missing file', async () => {
const envKey = `TEST_ENV_${Date.now()}`;
const jsFile = createTmpFile(`console.log('ENV: ' + process.env.${envKey});`);
const missingEnvFile = path.join(tmpdir.path, `missing-${Date.now()}.env`);
const { done, restart } = runInBackground({
args: ['--watch-path', tmpdir.path, `--env-file-if-exists=${missingEnvFile}`, jsFile],
});

try {
const { stderr, stdout } = await restart();

assert.doesNotMatch(stderr, /ENOENT: no such file or directory, watch/);
assert.deepStrictEqual(stdout, [
'ENV: undefined',
`Completed running ${inspect(jsFile)}. Waiting for file changes before restarting...`,
]);
} finally {
await done();
}
});

it('should watch changes to a failing file', async () => {
const file = createTmpFile('throw new Error("fails");');
const { stderr, stdout } = await runWriteSucceed({
Expand Down
Loading