What does fs.watch() do?
In Node.js, fs.watch() is used to track changes in the filesystem, it "watches" files or folders and calls a callback when something changes.
Signature
javascript
fs.watch(filename[, options][, listener])Arguments:
filename, the path to the file or directory to watch.options(optional):persistent:trueby default, iffalse, the watch won't keep the Node.js process "alive";recursive:truewatches all subdirectories recursively (macOS and Windows only);encoding: the encoding for filenames ('utf8'by default).
listener, the callback invoked on changes.
Example
javascript
const fs = require('fs');
fs.watch('./data', (eventType, filename) => {
console.log(`Event: ${eventType}`);
console.log(`File changed: ${filename}`);
});Possible eventType values:
"rename", a file was renamed, created, or deleted;"change", a file was modified (for example, its content was updated).
A practical example
Watching a config file for changes:
javascript
fs.watch('config.json', (eventType) => {
if (eventType === 'change') {
console.log('The config file was updated! Reloading settings...');
// For example, re-read the JSON here
}
});Quirks and limitations
- Behavior depends on the OS Node.js uses the platform's native APIs:
inotifyon Linux,FSEventson macOS,ReadDirectoryChangesWon Windows. So events can differ slightly across platforms.
- Not every change is guaranteed to be caught, especially when many files change at once.
fs.watch()doesn't read the file's content, it only reports that something changed.- For more reliable watching (with buffering and handling of missed events), the chokidar library is a better choice, it's cross-platform and more stable.
Summary
fs.watch()is Node.js's built-in function for watching files and folders for changes. It calls a callback on"change"or"rename"events, and it's useful for things like:
- automatically reloading configuration,
- rebuilding a project when files change,
- monitoring logs or directories.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.