Node.js - how to watch a file/directory for changes

Published on

Sometimes you want to be notified if a file or directory gets updated/changed.

You can do this with fs.watch(). It takes a filename and a callback. The callback has a couple of params you want to use - eventType and fileName. You can pass in a directory (so fileName is more useful then).

const fs = require('fs');

// can be a filename or a directory...
const fileToWatch =  './your-file-to-watch.txt'

fs.watch(fileToWatch, (eventType, fileName) => {
  if (eventType === 'rename') {
    console.log(`${fileName} was added/deleted`);
  } else {
    console.log(`${fileName} was updated`);
  }
});