Watching Files with fs.watch() and fs.watchFile()
What you'll learn: How to monitor files and directories in Node.js so your program can react automatically when they change.
The Core Idea
Imagine you're developing a web server that needs to reload configuration files whenever they're edited, or a build tool that recompiles code when source files change. Instead of constantly checking files manually, Node.js lets your program "watch" them and receive notifications when modifications occur. The fs module provides two main approaches: fs.watch() and fs.watchFile().
fs.watch(): Event-Based Monitoring
fs.watch() uses operating system-level features to detect changes efficiently. It can watch both files and entire directories:
const fs = require('fs');
const watcher = fs.watch('./myfile.txt', (eventType, filename) => {
console.log(`Event: ${eventType}`);
console.log(`File: ${filename}`);
});
// Stop watching later
watcher.close();
The eventType is typically 'rename' (for creation/deletion/renaming) or 'change' (for content modifications).
fs.watchFile(): Polling-Based Alternative
fs.watchFile() uses stat polling (periodically checking file stats), making it more reliable across different platforms but less efficient:
fs.watchFile('./myfile.txt', (curr, prev) => {
console.log('File modified');
console.log('Previous mtime:', prev.mtime);
console.log('Current mtime:', curr.mtime);
});
// Stop watching
fs.unwatchFile('./myfile.txt');
This method provides fs.Stats objects showing before-and-after file information.
When to Use Each
Use fs.watch() for performance when monitoring many files or directories. Use fs.watchFile() when you need cross-platform reliability or are watching network-mounted files where OS events might not work properly.
Key Takeaway: fs.watch() and fs.watchFile() let your Node.js programs respond to filesystem changes in real-time—watch uses efficient OS events while watchFile uses reliable polling, each suited to different scenarios.