Node.js fs.watchFile() Method

08 Oct, 2021
The fs.watchFile() method is used to continuously watch for changes on the given file. It has a callback listener that is called every time the file is accessed. It has an optional options parameter that can be used to specify properties like the interval on how often the file has to be polled and whether the process would continue as long as the file is being watched.
The listener has two arguments, that is the current stat object and the previous stat object. This can be used to compare the changes to the file. The modified file access time can be found from the fs.Stat object’s mtime property.
While watching a file, if it disappears and reappears, the previousStat of the disappearance callback will be the same as the previousStat of the appearance callback. This happens when the file is renamed and then renamed a second time back to its original name. It can also happen when the file is deleted and then restored back.
Syntax:
fs.watchFile(filename[, options], listener)
Parameters: This method accepts three parameters as mentioned above and described below:
filename: It is a String, Buffer or URL that denotes the filename of the file to be watched.options: It is an Object that can be used to modify the behavior of the method. It is an optional parameter. It has the following parameters: bigint: It is a Boolean value that is used to specify the numeric values of the fs.Stat object as BigInt values. The default value is false.persistent: It is a Boolean value that is used to specify if the process should continue as long as the file is being watched. The default value is true.interval: It is an integer that specifies the time interval between each poll to the target. It is specified in milliseconds. The default value is 5007.listener: It is function that is invoked when the file is accessed or modified. current: It is a fs.Stats object that denotes the current state of the file after being accessed or modified.previous: It is a fs.Stats object that denotes the previous state of the file before being accessed or modified.
filename: It is a String, Buffer or URL that denotes the filename of the file to be watched.
options: It is an Object that can be used to modify the behavior of the method. It is an optional parameter. It has the following parameters: bigint: It is a Boolean value that is used to specify the numeric values of the fs.Stat object as BigInt values. The default value is false.persistent: It is a Boolean value that is used to specify if the process should continue as long as the file is being watched. The default value is true.interval: It is an integer that specifies the time interval between each poll to the target. It is specified in milliseconds. The default value is 5007.
bigint: It is a Boolean value that is used to specify the numeric values of the fs.Stat object as BigInt values. The default value is false.
persistent: It is a Boolean value that is used to specify if the process should continue as long as the file is being watched. The default value is true.
interval: It is an integer that specifies the time interval between each poll to the target. It is specified in milliseconds. The default value is 5007.
listener: It is function that is invoked when the file is accessed or modified. current: It is a fs.Stats object that denotes the current state of the file after being accessed or modified.previous: It is a fs.Stats object that denotes the previous state of the file before being accessed or modified.
current: It is a fs.Stats object that denotes the current state of the file after being accessed or modified.
previous: It is a fs.Stats object that denotes the previous state of the file before being accessed or modified.
Return Value: It returns a fs.StatWatcher object when the function is successfully called.
Below examples illustrate the fs.watchFile() method in Node.js:Example 1: This example shows the usage of the watchFile() method along with its parameters.
// Node.js program to demonstrate// the fs.watchFile() method  // Import the filesystem moduleconst fs = require('fs');  fs.watchFile(    // The name of the file to watch  "example_file.txt",    // The options parameter is used to   //modify the behaviour of the method  {    // Specify the use of big integers    // in the Stats object     bigint: false,      // Specify if the process should     // continue as long as file is    // watched    persistent: true,      // Specify the interval between    // each poll the file    interval: 4000,  },  (curr, prev) => {    console.log("\nThe file was edited");      // Show the time when the file was modified    console.log("Previous Modified Time", prev.mtime);    console.log("Current Modified Time", curr.mtime);      console.log(      "The contents of the current file are:",      fs.readFileSync("example_file.txt", "utf8")    );  });  // Make Changes to the file for the first timefs.writeFileSync("example_file.txt",   "File Contents are Edited");  // Make Changes to the file for the second timesetTimeout(  () => fs.writeFileSync("example_file.txt",          "File Contents are Edited Again"),  5000);
Output:
The file was edited
Previous Modified Time 2020-05-30T07:52:14.587Z
Current Modified Time 2020-05-30T08:01:40.948Z
The contents of the current file are: File Contents are Edited

The file was edited
Previous Modified Time 2020-05-30T08:01:40.948Z
Current Modified Time 2020-05-30T08:01:45.950Z
The contents of the current file are: File Contents are Edited Again

Example 2: This example shows the file modification time when a file is renamed and then renamed back to its original name, causing a file disappearance and reappearance.
// Node.js program to demonstrate // the fs.watchFile() method  // Import the filesystem moduleconst fs = require('fs');  fs.watchFile("example_file.txt", (curr, prev) => {  console.log("\nThe File was modified");  console.log("Previous Modification Time", prev.mtime);  console.log("Current Modification Time", curr.mtime);});  // Renaming the file to a new namesetTimeout(  () => fs.renameSync("example_file.txt",           "new_file.txt"),  1000);  // Renaming the file back to its old namesetTimeout(  () => fs.renameSync("new_file.txt",           "example_file.txt"),  6000);
Output:
Previous Modification Time 2020-05-30T08:01:45.950Z
Current Modification Time 1970-01-01T00:00:00.000Z

The File was modified
Previous Modification Time 2020-05-30T08:01:45.950Z
Current Modification Time 2020-05-30T08:01:45.950Z

Reference: https://nodejs.org/api/fs.html#fs_fs_watchfile_filename_options_listener
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Installation of Node.js on Windows
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React