How to watch for file changes in Node.js
· Category: Node.js
Short answer
Use fs.watch() for efficient event-based file watching or fs.watchFile() for polling-based watching on systems where native events are unreliable.
Steps
- Import fs:
const fs = require('fs');. - Watch a file:
fs.watch('file.txt', (eventType, filename) => { console.log(eventType, filename); });. - Watch a directory recursively on supported platforms:
fs.watch('dir', { recursive: true }, callback);. - Use
fs.watchFile()for polling iffs.watch()is unstable on your OS. - Always handle errors and close watchers with
.close()when no longer needed.
Tips
fs.watch()is not 100% consistent across macOS, Linux, and Windows; test on your target platform.- Debounce change events because saving a file may trigger multiple rapid events.
Common issues
- On some systems,
fs.watch()emits the filename as null or triggers twice for a single change. - Holding too many watchers open consumes file descriptors and can exhaust OS limits.