![]() |
VOOZH | about |
The fs.watch() method is an inbuilt application programming interface of fs module which is used to continuously watch for changes in the given file or directory. It returns a fs.FSWatcher object that can be used to track the changes in the file.
It has an optional listener as the third argument that can be used to get the changes that take place. This listener has two arguments, one is the name of the file or directory that is modified and the other is the type of modification. While watching a file, if it disappears and reappears, the 'rename' event is emitted, and if the file contents are modified the 'change' event is emitted.
Note: This method is unreliable and may show multiple events in the listener for each modification.
Syntax:
fs.watch( filename[, options][, listener] )
Parameters: This method accepts three parameters as mentioned above and described below:
Return Value: It returns a fs.StatWatcher object when the function is successfully called.
Below examples illustrate the fs.watch() method in Node.js:
Example 1: This example shows the usage of the watch() method on a file.
Output: Note that this method is unreliable and may show multiple events for every modification.
The file example_file.txt was modified! The type of change was: rename The file example_file.txt was modified! The type of change was: rename The file example_file.txt was modified! The type of change was: change
Example 2: This example shows the usage of the watch() method on a directory.
Output: Note that this method is unreliable and may show multiple events for every modification.
The file ex1.txt was modified! The type of change was: change The file ex2.txt was modified! The type of change was: rename The file new_ex2.txt was modified! The type of change was: rename
Reference: https://nodejs.org/api/fs.html#fs_fs_watch_filename_options_listener