Q1. How do you watch for file changes in Node.js?
Use fs.watch() or fs.watchFile(). fs.watch() is more efficient and uses native OS notifications. Example:
fs.watch('file.txt', (eventType, filename) => { console.log(eventType, filename); }); eventType can be 'change' or 'rename'. Note that filename may be null on some platforms.Q2. What's the difference between fs.watch() and fs.watchFile()?
fs.watch() uses native OS file watching (more efficient, real-time, but less consistent across platforms). fs.watchFile() uses polling (checks file stats periodically), which is slower but more consistent. fs.watch() is generally preferred, but you might use fs.watchFile() when you need more control or on network file systems.
Q3. How do you watch an entire directory?
Both fs.watch() and fs.watchFile() can watch directories. For fs.watch():
fs.watch('./mydir', (eventType, filename) => { console.log(eventType, filename); }); Note that filename might be just the filename, not the full path. You may need to combine with path module to get full paths.Q4. How do you stop watching a file?
For fs.watch(), the returned object has a .close() method:
const watcher = fs.watch('file.txt', ...); watcher.close(); For fs.watchFile(), use fs.unwatchFile('file.txt') or fs.unwatchFile('file.txt', listener) to remove a specific listener.Q5. What are common use cases for file watching?
File watching is used in development tools (like nodemon that restarts server on file changes), build systems (compiling on save), log monitoring, configuration file hot-reloading, and file synchronization tools. It enables real-time responses to file system changes without manual intervention.
