Skip to main content

fs.FSWatcher in Node.js

fs.FSWatcher is an EventEmitter that is used to watch the changes/updates in a directory. fs.watch() will emit a 'change' event when a file is modified. We will get a better understanding by looking into it's implementation.

 var fs = require('fs');
 var watcher = fs.watch(__dirname);

Here we have assigned a directory that needs to be watched, which means if there are any modifications to be made in this directory the fs.watch() (i.e watcher in our case) function will emit a change event.

watcher.on('change', function name(event, filename){
        // your code here
}); 

OR 

 fs.watch('./tmp', { encoding: 'buffer'}, (eventType, filename) => {
   if(filename){
     // your code here
   }
});
 
In the example above scenario  we are providing the filename as a buffer other wise filename will be a UTF-8 string.

Hence , FSWatcher is a simple event emitter with convenient stat()/close() methods. Let's take a deeper look now into the close method

 Close():

 watcher.close() 
 
In case you want to stop watching the current being watched file/directory you can call the close()  method which will stop the watcher looking for changes.

Error event:  

In case an error orrcurs while watching the file error event is emitted.

You can also take a look at Node.JS offical document on FSWatcher




Comments

Popular posts from this blog

Release 0.1

Release 0.1 was about editing the Filer project. That project used var for declaring every property. Even the constants were declared using var.  According to the new updates, const should be used to declare a variable which will not be reassigned later. Hence, if you declare a variable as const and end up reassigning it by mistake your code will throw an error. Whereas, let is a block scope local variable and can be reassigned easily. For more details about const, let and var click here. For the release 0.1 I have updated the implementation.js file, now it declares its constants using const. Here is the  link to the pull request I made for the above discussed updates. This was the first time I made a pull request using git hub and it was a bit overwhelming and confusing for me as there were a lot of steps. Hence I have shortened the steps and made a note of it which I can use when I make my second pull request:: 1. File an issue for a bug you find. 2. Create a fork