3

I have a simple file watcher build with chokidar

require('chokidar').watch('./target.txt', {}).on('all', function(event, path) {
  console.log(event, path);
}).on('ready', function() {
  console.log('ready');
});

It causes change event every time when I re-save file even without changes. Is there a way to make this fire events only if actual content has been changed?

1 Answer 1

6

You can use the stats parameter delivered on add and change. This will only work for changes on the size of the file, which should be enough for the vast majority of cases.

   var watchSize = 0;

    require('chokidar').watch('./target.txt', {}).on('all', function(event, path, stats) {  

        if(stats && stats.size != watchSize) {
            watchSize = stats.size;
            console.log(event);
        }
    }).on('ready', function(path, stats) {
      console.log('ready');
    });

If the few remaining situations are indeed relevant for your case and you have no performance concerns, you can use something like this (following the suggestion in the comments):

var crypto   = require("crypto");
var fs       = require("fs");
var chokidar = require("chokidar");

watchFile("./target.txt");

//----------------------------------------------------
function watchFile(filePath){

    var watchHash;

    chokidar.watch(filePath, {}).on("all", function(event, path, stats) {

        if (event == "add" || event == "change"){

            getHash(filePath, function(hash){
                if (hash != watchHash){
                    watchHash = hash;
                    console.log(event);
                }
            });
        }
    });
}

//----------------------------------------------------
function getHash(filePath, callback){

    var stream = fs.ReadStream(filePath);   
    var md5sum = crypto.createHash("md5");

    stream.on("data", function(data) {
        md5sum.update(data);
    });

    stream.on("end", function() {
        callback(md5sum.digest("hex"));
    });
}

This seems a bit much, though.

Sign up to request clarification or add additional context in comments.

6 Comments

A good check would be storing a hash (md5 for example) of the file and comparing when the change is triggered.
Yes, good suggestion. Still, that requires reading the file, so i'd only do it when file size hasn't changed.
Nice.Just curious,any idea under what cases does the file size remain the same but the file has indeed been changed?
True!Why din't I think of that!
Changes with remaining size make sense for me. If it is a config file I can change one number property from 0 to 1 for example. I want to be notified about that. But I don't want to be bothered with unnecessary notifications
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.