Learn how to check for changes, deletions, updates or creation of files and directories on the system using Electron Framework.

Watch Files and Directories with Electron Framework

File and Folder Watcher continuously monitors one or more folders for new files. When new files arrive, File and Folder Watcher then triggers a custom action.

Library

To handle this task, we are going to use the node.js chokidar library which is a lot better than the fs.watchFile function of node.js , but why ?

Node.js fs.watch:

  • Doesn't report filenames on OS X.
  • Doesn't report events at all when using editors like Sublime on OS X.
  • Often reports events twice.
  • Emits most changes as rename.
  • Has a lot of other issues.
  • Does not provide an easy way to recursively watch file trees.

Node.js fs.watchFile:

  • Almost as bad at event handling.
  • Also does not provide any recursive watching.
  • Results in high CPU utilization.

Chokidar resolves these problems, therefore we are going to use this in our project to watch for folders and files etc. To include it in your project execute the following command in your command line :

npm install chokidar --save

Then we'll be able to use it from javascript in our electron project using :

var fileWatcher = require("chokidar");

Watching folders and files

To create a watcher, use the chokidar.watch method and add the properly listeners, to know more about the listeners and all the methods, read the library documentation here.

The following function will create an event watcher for a given folder path:

function StartWatcher(path){
      var chokidar = require("chokidar");

      var watcher = chokidar.watch(path, {
          ignored: /[\/\\]\./,
          persistent: true
      });

      function onWatcherReady(){
          console.info('From here can you check for real changes, the initial scan has been completed.');
      }
            
      // Declare the listeners of the watcher
      watcher
      .on('add', function(path) {
            console.log('File', path, 'has been added');
      })
      .on('addDir', function(path) {
            console.log('Directory', path, 'has been added');
      })
      .on('change', function(path) {
           console.log('File', path, 'has been changed');
      })
      .on('unlink', function(path) {
           console.log('File', path, 'has been removed');
      })
      .on('unlinkDir', function(path) {
           console.log('Directory', path, 'has been removed');
      })
      .on('error', function(error) {
           console.log('Error happened', error);
      })
      .on('ready', onWatcherReady)
      .on('raw', function(event, path, details) {
           // This event should be triggered everytime something happens.
           console.log('Raw event info:', event, path, details);
      });
}

Now, we'll need a path to watch. Create a simple button that will start the Folder Browser of the system to choose a path and start the watcher using the following code:

var dialog = require('electron').remote;
dialog.showOpenDialog({
    properties: ['openDirectory']
},function(path){
    if(path){
        // Start to watch the selected path
        StartWatcher(path[0]);
    }else {
        console.log("No path selected");
    }
});

The system folder browser should appear and if a folder is selected, the watcher will start to scan for folders and files inside the given path. Then it will start to watch for all the given events.

The basic functions should be displayed in the console :

Electron file watcher

To see the previos project, feel free to explore it in the official electron examples of our code world in github here. Have fun


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors