How to watch a file for changes using Node.js?

Published March 28, 2021

To watch for any changes to a file, you can use the watchFile() method from the fs (filesystem) module in Node.js.

// require fs (filesystem) module
const fs = require("fs");

// use fs.watchFile() method to look for changes
fs.watchFile("./myfolder/myFile.txt", (currentStat, prevStat) => {
  console.log("Current File Stats: ", currentStat);
  console.log("Previous File Stats:", prevStat);
});

Imagine you have a file named myFile.txt inside the myFolder directory and you want to check for changes that are happening to the file.

For that, we use the fs.watchFile() method and pass the path to the file as the first argument, and then pass the callback function like this,

// require fs (filesystem) module
const fs = require("fs");

// use fs.watch() method to look for changes
fs.watchFile("./myfolder/myFile.txt", () => {
  // some good stuff here! 😃
});

We have now defined the path of the file we want to check for changes. Whenever there is a change to the file, the callback function is called and passed with two arguments:

  • The first one is current, which tells all the statistics on the current file.
  • The second parameter is previous. which tells all the statistics on the previous file.

It looks like this,

// require fs (filesystem) module
const fs = require("fs");

// use fs.watchFile() method to look for changes
fs.watchFile("./myfolder/myFile.txt", (currentStat, prevStat) => {
  console.log("Current File Stats: ", currentStat);
  console.log("Previous File Stats:", prevStat);
});

See the above code live in repl.it.

That's all! 😃

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter