Node.js › File System & File Processing
How would you implement a file-watching feature in Node.js using fs.watch(), and what are its known cross-platform limitations?
AdvancedAnswer
fs.watch() monitors a file or directory for changes, emitting events when something is modified, renamed, or removed -- but its behavior is notoriously inconsistent across operating systems (event types and reliability differ between Linux, macOS, and Windows, and it can occasionally miss rapid successive changes or fire duplicate events), which is why many production tools use a more robust third-party library like chokidar that normalizes these platform differences.
const fs = require('node:fs');
fs.watch('./config', (eventType, filename) => {
console.log(`${eventType} detected on ${filename}`);
reloadConfig();
});
// More robust cross-platform alternative
const chokidar = require('chokidar');
chokidar.watch('./config').on('change', reloadConfig);Real-world example A development server's hot-reload feature initially used fs.watch() directly, but switched to chokidar after developers on different operating systems reported inconsistent reload behavior, since chokidar normalizes the platform-specific quirks fs.watch() exposes directly.