Full answer
Options in Node:
- fs.watch(path, options, listener) or the promise version fs.promises.watch(path, { signal }), which returns an async iterator. It uses inotify on Linux, FSEvents on macOS and ReadDirectoryChangesW on Windows. It is efficient, but behaviour differs by platform.
- fs.watchFile(path, { interval }, listener): polls stat information. It works on network drives where native events do not, but costs CPU.
- node --watch app.js restarts the process when a imported file changes, and node --watch-path=./src targets directories. It is for development.
- chokidar and similar libraries normalise events, handle atomic saves and globs. Many tools use it.
Things that surprise people:
- Event names are 'rename' and 'change'. 'rename' covers create, delete and move. You must stat the path to know what happened.
- One save often produces two or more events, because editors write a temporary file, truncate, write and rename. Debounce by file name (wait 50 to 200 ms of silence) before reacting.
- filename can be null on some platforms, so guard for it.
- The recursive option works on Linux since Node 20, and on macOS and Windows for a longer time. Test on your platform.
- Watching a file that is replaced (an atomic save) can lose the watch on some systems. Watch the directory instead.
- Always keep a way to stop the watcher (close() or an AbortSignal) so the process can exit.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { setTimeout: sleep } = require('node:timers/promises');
async function main() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'watch-'));
const controller = new AbortController();
const kinds = new Set(); // which event kinds we saw
const reloads = []; // debounced reactions
const timers = new Map();
(async () => {
try {
for await (const { eventType, filename } of fs.promises.watch(dir, { signal: controller.signal })) {
kinds.add(`${eventType}:${filename}`);
clearTimeout(timers.get(filename));
timers.set(filename, setTimeout(() => reloads.push(filename), 60)); // debounce per file
}
} catch (err) {
if (err.name !== 'AbortError') throw err;
}
})();
await sleep(50);
const file = path.join(dir, 'config.json');
fs.writeFileSync(file, '{"v":1}'); // create + write
await sleep(30);
fs.appendFileSync(file, ' '); // a second change quickly after
await sleep(250);
fs.rmSync(file); // delete
await sleep(250);
controller.abort();
await sleep(20);
console.log('event kinds seen:', [...kinds].sort().join(' | '));
console.log('debounced reactions:', reloads.length, 'for', [...new Set(reloads)].join(','));
fs.rmSync(dir, { recursive: true });
}
main();The script creates, edits and deletes a file. Several raw events arrive, but the debounce turns each burst into one reaction. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): event kinds seen: change:config.json | rename:config.json debounced reactions: 2 for config.json
Key points
- fs.watch uses OS events and reports 'rename' and 'change'.
- One save can fire several events, so debounce per file.
- Watch the directory to survive atomic saves.
- watchFile polls and works on network drives.
- Close watchers or abort them so the process can exit.
Common mistakes
- Reacting to every raw event and rebuilding many times.
- Assuming 'rename' means only a rename.
- Watching a single file and losing it after an atomic save.
- Forgetting to close the watcher so the process never exits.
- Testing only on one operating system.
Follow-ups
- How does node --watch decide what to restart?
- How would you watch a large directory tree without hitting limits?
- Why can inotify watches run out on Linux?
Tips
- Mention duplicate events early.
- Say 'debounce' and 'watch the directory'.
- Name chokidar as the common library.