This article explains how to monitor file changes and trigger actions using Node.js’s standard library “fs.watch”.
The following is sample code from the official documentation File system | Node.js v16.1.0 Documentation with some modifications.
const fs = require('fs');
fs.watch('./file.txt', (eventType, filename) => {
console.log(`event type is: ${eventType}`);
if (filename) {
console.log(`filename provided: ${filename}`);
} else {
console.log('filename not provided');
}
});
This monitors the file ”./file.txt” in the current directory and logs when changes occur.
For this article, I’ll implement a sample that performs an action when the file changes - specifically, waiting for file changes and continuing the script when a change occurs. Here’s the code example. I wrote it to be as simple as possible, eliminating unnecessary code and implementing only the minimum functionality.
(async function(){
await (new Promise((resolve) => {
fs.watch('./file', (e, f) => { resolve() })
})); // wait for file change
console.log("changed.");
})();
Since fs.watch doesn’t have a synchronous version like filereadsync, we implement it by combining it with a promise. We wait for the promise with “await”, and when the ./file changes, we execute resolve() to exit the promise and continue to the console.log.
In this article, we implemented a simple file change waiting mechanism using built-in Node.js libraries. However, if you want to create a command-line tool with this functionality or build something more complex, I recommend checking out other existing libraries and command-line tools, such as bash’s “inotifywait” or Node.js library “nodemon”.