Skip to content

Commit

Permalink
fs: fix nonNativeWatcher watching folder with existing files
Browse files Browse the repository at this point in the history
PR-URL: nodejs#45500
Reviewed-By: Yagiz Nizipli <[email protected]>
  • Loading branch information
MoLow committed Jan 5, 2023
1 parent 1c6772a commit 551a92d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/internal/fs/recursive_watch.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,9 @@ class FSWatcher extends EventEmitter {
this.emit('change', 'rename', pathRelative(this.#rootPath, file));
} else if (currentStats.isDirectory()) {
this.#watchFolder(file);
} else {
// Watching a directory will trigger a change event for child files)
this.emit('change', 'change', pathRelative(this.#rootPath, file));
}
});
}
Expand Down
30 changes: 30 additions & 0 deletions test/parallel/test-fs-watch-recursive.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,36 @@ process.on('exit', function() {
assert(watcherClosed, 'watcher Object was not closed');
});

(async () => {
// Watch a folder and update an already existing file in it.

const rootDirectory = fs.mkdtempSync(testDir + path.sep);
const testDirectory = path.join(rootDirectory, 'test-0');
fs.mkdirSync(testDirectory);

const testFile = path.join(testDirectory, 'file-1.txt');
fs.writeFileSync(testFile, 'hello');

const watcher = fs.watch(testDirectory, { recursive: true });
let watcherClosed = false;
watcher.on('change', common.mustCallAtLeast(function(event, filename) {
// Libuv inconsistenly emits a rename event for the file we are watching
assert.ok(event === 'change' || event === 'rename');

if (filename === path.basename(testFile)) {
watcher.close();
watcherClosed = true;
}
}));

await setTimeout(common.platformTimeout(100));
fs.writeFileSync(testFile, 'hello');

process.once('exit', function() {
assert(watcherClosed, 'watcher Object was not closed');
});
})().then(common.mustCall());

(async () => {
// Assert recursive watch does not leak handles
const rootDirectory = fs.mkdtempSync(testDir + path.sep);
Expand Down

0 comments on commit 551a92d

Please sign in to comment.