Watching files
fs.watch tells you when a file or folder changes so you can react automatically.
In this page:
Syntax
fs.watch('path', (eventType, filename) => {
// handle change or rename
});
Watching files
fs.watch(path, listener) emits change and rename events, and fs.watchFile polls for changes. Behaviour differs by platform and events can fire multiple times, so debounce them. Tools like nodemon are built on this.
Note:
Debounce watch handlers because one save can trigger several events.
Example: Watching files
const fs = require("fs");
fs.writeFileSync("watched.txt", "v1");
const watcher = fs.watch("watched.txt", (event) => {
console.log("event:", event);
watcher.close();
});
setTimeout(() => fs.writeFileSync("watched.txt", "v2"), 20);
// Output:
// event: change
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Relying on identical events across platforms
- Not closing the watcher
- Handling duplicate events
Chapter Summary
- fs.watch reports changes
- Events may repeat
- Debounce handlers
- Close watchers when done
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: