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

  1. Import fs: const fs = require('fs');.
  2. Watch a file: fs.watch('file.txt', (eventType, filename) => { console.log(eventType, filename); });.
  3. Watch a directory recursively on supported platforms: fs.watch('dir', { recursive: true }, callback);.
  4. Use fs.watchFile() for polling if fs.watch() is unstable on your OS.
  5. 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.