Skip to content

Commit 147d810

Browse files
authoredNov 27, 2022
fs: fix nonNativeWatcher watching folder with existing files
PR-URL: #45500 Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
1 parent 8264f0b commit 147d810

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
 

‎lib/internal/fs/recursive_watch.js

+3
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,9 @@ class FSWatcher extends EventEmitter {
199199
this.emit('change', 'rename', pathRelative(this.#rootPath, file));
200200
} else if (currentStats.isDirectory()) {
201201
this.#watchFolder(file);
202+
} else {
203+
// Watching a directory will trigger a change event for child files)
204+
this.emit('change', 'change', pathRelative(this.#rootPath, file));
202205
}
203206
});
204207
}

‎test/parallel/test-fs-watch-recursive.js

+31
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,37 @@ const tmpdir = require('../common/tmpdir');
2222
const testDir = tmpdir.path;
2323
tmpdir.refresh();
2424

25+
(async () => {
26+
// Watch a folder and update an already existing file in it.
27+
28+
const rootDirectory = fs.mkdtempSync(testDir + path.sep);
29+
const testDirectory = path.join(rootDirectory, 'test-0');
30+
fs.mkdirSync(testDirectory);
31+
32+
const testFile = path.join(testDirectory, 'file-1.txt');
33+
fs.writeFileSync(testFile, 'hello');
34+
35+
const watcher = fs.watch(testDirectory, { recursive: true });
36+
let watcherClosed = false;
37+
watcher.on('change', common.mustCallAtLeast(function(event, filename) {
38+
// Libuv inconsistenly emits a rename event for the file we are watching
39+
assert.ok(event === 'change' || event === 'rename');
40+
41+
if (filename === path.basename(testFile)) {
42+
watcher.close();
43+
watcherClosed = true;
44+
}
45+
}));
46+
47+
await setTimeout(common.platformTimeout(100));
48+
fs.writeFileSync(testFile, 'hello');
49+
50+
process.once('exit', function() {
51+
assert(watcherClosed, 'watcher Object was not closed');
52+
});
53+
})().then(common.mustCall());
54+
55+
2556
(async () => {
2657
// Add a file to already watching folder
2758

0 commit comments

Comments
 (0)
Please sign in to comment.