Last Updated: February 25, 2016
·
10.01K
· vvo

Node.js, watching for file create/delete

Watching for file create and delete used to be simple in node.js 0.6, all you had to do is use the fs.watchFile.

Now if you want to do that in node 0.8, let's say that all you have is a file path and you want to be notified each time it is created or removed.

function watchFile(filepath, oncreate, ondelete) {
  var
    fs = require('fs'),
    path = require('path'),
    filedir = path.dirname(filepath),
    filename = path.basename(filepath);

  fs.watch(filedir, function(event, who) {
    if (event === 'rename' && who === filename) {
      if (fs.existsSync(filepath)) {
        oncreate();
      } else {
        ondelete();
      }
    }
  }
}

1 Response
Add your response

Thanks, this is very useful !

over 1 year ago ·