Node.js fs.unwatchFile() Method
Last Updated :
08 Oct, 2021
The fs.unwatchFile() method is used to stop watching for changes on the given file. An optional listener parameter can be specified to remove only the specified listener from the file. Otherwise, all the listeners associated with the file are removed. If the file is not being watched when this function is used, then it does not perform any operation and throw any error.
Syntax:
fs.unwatchFile(filename[, listener])
Parameters: This method accepts two parameters as mentioned above and described below:
- filename: It is a String, Buffer or URL that denotes the file that has to be stopped from watching.
- listener: It is a function that specifies the listener previously attached using the fs.watchFile() function. If specified, only this particular listener is removed. It is an optional parameter.
Below examples illustrate the fs.unwatchFile() method in Node.js.
Example 1:
const fs = require( 'fs' );
fs.watchFile( "example_file.txt" , (curr, prev) => {
console.log( "\nThe file was edited" );
console.log( "Previous Modified Time:" , prev.mtime);
console.log( "Current Modified Time:" , curr.mtime);
});
setTimeout(
() => fs.writeFileSync( "example_file.txt" ,
"File Contents are Edited" ),
1000
);
setTimeout(() => {
fs.unwatchFile( "example_file.txt" );
console.log( "\n> File has been stopped watching" );
}, 6000);
setTimeout(
() => fs.writeFileSync( "example_file.txt" ,
"File Contents are Edited Again" ),
7000
);
|
Output:
The file was edited
Previous Modified Time: 2020-05-30T08:43:28.216Z
Current Modified Time: 2020-05-30T08:43:37.208Z
File has been stopped watching
Example 2:
const fs = require( 'fs' );
let listener1 = (curr, prev) => {
console.log( "Listener 1: File Modified" );
};
let listener2 = (curr, prev) => {
console.log( "Listener 2: File Modified" );
};
fs.watchFile( "example_file.txt" , listener1);
fs.watchFile( "example_file.txt" , listener2);
setTimeout(
() => fs.writeFileSync( "example_file.txt" ,
"File Contents are Edited" ),
1000
);
setTimeout(() => {
fs.unwatchFile( "example_file.txt" , listener1);
console.log( "\n> Listener 1 has been stopped!\n" );
}, 6000);
setTimeout(
() => fs.writeFileSync( "example_file.txt" ,
"File Contents are Edited Again" ),
8000
);
|
Output:
Listener 1: File Modified
Listener 2: File Modified
Listener 1 has been stopped!
Listener 2: File Modified
Reference: https://nodejs.org/api/fs.html#fs_fs_unwatchfile_filename_listener
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...