Watch Files and Directories with Node.js

By  on  

Watching a file or directory for changes is an important part of automation.  We all enjoy using our favorite CSS preprocessor's "watch" feature -- we can still refresh the page and see our changes as though we were simply writing in pure CSS.  Node.js makes both file and directory watching easy -- but it's a bit more difficult than you may think.

Simply put:  Node.js' watching features aren't consistent or performant yet, which the documentation admits.  The good news:  a utility called chokidar stabilizes file watching and provides added insight into what has happened.  chokidar provides a wealth of listeners;  instead of providing boring reduced examples, here's what chokidar provides you:

var chokidar = require('chokidar');

var watcher = chokidar.watch('file, dir, or glob', {
  ignored: /[\/\\]\./, persistent: true
});

var log = console.log.bind(console);

watcher
  .on('add', function(path) { log('File', path, 'has been added'); })
  .on('addDir', function(path) { log('Directory', path, 'has been added'); })
  .on('change', function(path) { log('File', path, 'has been changed'); })
  .on('unlink', function(path) { log('File', path, 'has been removed'); })
  .on('unlinkDir', function(path) { log('Directory', path, 'has been removed'); })
  .on('error', function(error) { log('Error happened', error); })
  .on('ready', function() { log('Initial scan complete. Ready for changes.'); })
  .on('raw', function(event, path, details) { log('Raw event info:', event, path, details); })

// 'add', 'addDir' and 'change' events also receive stat() results as second
// argument when available: http://nodejs.org/api/fs.html#fs_class_fs_stats
watcher.on('change', function(path, stats) {
  if (stats) console.log('File', path, 'changed size to', stats.size);
});

// Watch new files.
watcher.add('new-file');
watcher.add(['new-file-2', 'new-file-3', '**/other-file*']);

// Un-watch some files.
watcher.unwatch('new-file*');

// Only needed if watching is `persistent: true`.
watcher.close();

// One-liner
require('chokidar').watch('.', {ignored: /[\/\\]\./}).on('all', function(event, path) {
  console.log(event, path);
});

What a wealth of handles, especially when you've experienced the perils of `fs` watch functionality.  File watching is essential to seamless development and chokidar makes life easy!

Recent Features

  • By
    How to Create a RetroPie on Raspberry Pi – Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

  • By
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

Incredible Demos

  • By
    HTML5’s window.postMessage API

    One of the little known HTML5 APIs is the window.postMessage API.  window.postMessage allows for sending data messages between two windows/frames across domains.  Essentially window.postMessage acts as cross-domain AJAX without the server shims. Let's take a look at how window.postMessage works and how you...

  • By
    jQuery Chosen Plugin

    Without a doubt, my least favorite form element is the SELECT element.  The element is almost unstylable, looks different across platforms, has had inconsistent value access, and disaster that is the result of multiple=true is, well, a disaster.  Needless to say, whenever a developer goes...

Discussion

  1. This tool was missing in Node.js, with it, it will be easier to play and manipulate with the directory structure and files.

  2. ravindranath

    The term “chokidar” seems to be a Hindi word, which literally means watcher. :)

  3. I have try fs.watch function of nodejs, it’s work fine but can you let me watcher work after complete change.

    fs.watch function start working when changes start.

  4. One of my favorite libraries. Keep spreading the good news!

  5. Jamie

    you can now also watch for file changes on a remote server using this module:

    https://www.npmjs.com/package/remote-file-watcher

  6. abhishek

    Is it possible to get process id or name from chokidar? I mean the process which updated the file system.

  7. Elia

    Hello!

    I’ve created an app using javascript. What I want to do is to continuously check the state of a directory. Since I’m not able to do this in javascript for security reasons I was thinking of using node.js. Is it possible to run run node.js in the background while javascript continues?

    Thanks

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!