How to Watch File Changes in Node.js Using fs.watch
In Node.js, you can watch file changes using the
fs.watch method from the built-in fs module. It lets you listen for changes like edits or renames on a file or directory and run a callback when changes happen.Syntax
The fs.watch function watches for changes on a file or directory. It takes three main parts:
filename: The path to the file or folder to watch.options: Optional settings like encoding or whether to watch recursively.listener: A callback function that runs when a change happens. It receives the event type and filename.
javascript
fs.watch(filename[, options], (eventType, filename) => {
// Your code here
});Example
This example watches a file named example.txt. When the file changes, it logs the type of change and the filename.
javascript
import fs from 'fs'; const filename = 'example.txt'; fs.watch(filename, (eventType, fname) => { if (fname) { console.log(`File ${fname} changed with event: ${eventType}`); } else { console.log(`File changed with event: ${eventType}`); } }); console.log(`Watching for changes on ${filename}...`);
Output
Watching for changes on example.txt...
File example.txt changed with event: change
Common Pitfalls
Some common mistakes when using fs.watch include:
- Not handling the case when
filenamein the callback isnull. - Expecting
fs.watchto be 100% reliable; it may miss some events on some platforms. - Using
fs.watchon network drives or unsupported file systems can cause issues. - Not closing the watcher when done, which can cause resource leaks.
For more reliable watching, consider fs.watchFile or third-party libraries like chokidar.
javascript
/* Wrong way: Not checking if filename is null */ fs.watch('file.txt', (eventType, filename) => { console.log(`Changed: ${filename}`); // filename can be null }); /* Right way: Check filename before using */ fs.watch('file.txt', (eventType, filename) => { if (filename) { console.log(`Changed: ${filename}`); } else { console.log('Filename not provided'); } });
Quick Reference
Tips for watching files in Node.js:
- Use
fs.watchfor simple, event-driven watching. - Pass
{ recursive: true }option to watch folders and subfolders on supported platforms. - Always check if
filenameis provided in the callback. - Close the watcher with
watcher.close()when done. - For complex needs, use libraries like
chokidarfor better cross-platform support.
Key Takeaways
Use fs.watch from Node.js fs module to watch file or directory changes.
Always check if the filename argument in the callback is not null before using it.
fs.watch may miss some events; consider alternatives for critical use cases.
Close watchers when no longer needed to free system resources.
For advanced watching, use third-party libraries like chokidar.