Skip to content Skip to sidebar Skip to footer

Detect File Content Changes From Node.js

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

Solution 1:

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");

//----------------------------------------------------functionwatchFile(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);
                }
            });
        }
    });
}

//----------------------------------------------------functiongetHash(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.

Post a Comment for "Detect File Content Changes From Node.js"