Listening to changes in Directory using Node.js

What do we really want to achieve ?

In this topic we are going listen changes in directory using node.js.

What are applications of it in real life ?

  • Many time you want to refresh user interface  to list changed folders when you are creating something like file manager.
  • If you implement  it on server to check if something changed, like you can enhance security of website by watching a folder of change.If any change is made in particular server directory then this code will send you email that  somebody has inserted script or made changes in existing files.is not it amazing?

What is needed to implement this functionality ?

  • You need to run

    npm install chokidar --save

In my implementation I used it with react.js, redux in an electron.js project. What I did here is that whenever a change is made in particular path it will dispatch a redux event which can be listened by other components registered to listen.

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { FileChange } from '../actions/filechange'
const storage = require('electron-json-storage');
const ipcRenderer = require('electron').ipcRenderer;
const remote = require('electron').remote;
const BrowserWindow = remote.BrowserWindow;

class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false,
    };
    
  }
  
  componentDidMount() {

    storage.get('watch_folder', (error, data) => {
      if (data)
        this.StartWatcher(data.path, this.props);
    });
  
  }

  

  StartWatcher = (path, props) => {
    var chokidar = require("chokidar");
    var watcher = chokidar.watch(path, {
      ignored: /[\/\\]\./,
      persistent: true,
      ignoreInitial: true
    });
    function fileHasChanged() {
      props.fileChange();
    }

    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', fileHasChanged)
      .on('addDir', function (path) {
        console.log('Directory', path, 'has been added');
      })
      .on('change', function (path) {
        console.log('File', path, 'has been changed');
      })
      .on('unlink', fileHasChanged)
      .on('unlinkDir', function (path) {
        console.log('Directory', path, 'has been removed');
      })
      .on('error', function (error) {
        console.log('Error happened', error);
      })
      .on('ready', onWatcherReady)

  }

  render() {
    return "You Ui part"
 } } 
const mapDispatchToProps = dispatch => { return { fileChange: () => FileChange(dispatch) } } 
export default connect(null, mapDispatchToProps)(Header)

Chokidar module provides listener for everything like adding ,deleting of folders and well as files. Here you can see StartWatcher method which contain

watcher
      .on('add', fileHasChanged)

it means whenever a new file is added it will call fileHasChanged method and fileHasChanged will despatch a redux event to update different ui components.

Hope you will like this and I am pretty sure you may implement may good things using this wonderful npm module.


Tagged with:
CodeNextGen
Written by Sanjeev Kumar

Get notifications about new posts on Twitter, RSS or Email.