Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS detect modified files

App loads user's text files and each of them can be changed by user. On app's start I want to check if any file was changed since last time. I think the most efficient way is to calculate checksum of each file and save to one json file. On app's start I will check each file checksum and compare it to data from json file Is there any more optimal/efficient way of doing this ? Or how exactly calculate file checksum ?

like image 984
Piotr Wójcik Avatar asked Dec 02 '16 23:12

Piotr Wójcik


1 Answers

Seems like this blog is a good read for you: http://blog.tompawlak.org/calculate-checksum-hash-nodejs-javascript

code example (from the blog):

var crypto = require('crypto');

function checksum (str, algorithm, encoding) {
    return crypto
        .createHash(algorithm || 'md5')
        .update(str, 'utf8')
        .digest(encoding || 'hex')
}

To read from a file and present its hash:

fs.readFile('test.dat', function (err, data) {
    checksum(data);         // e53815e8c095e270c6560be1bb76a65d
    checksum(data, 'sha1'); // cd5855be428295a3cc1793d6e80ce47562d23def
});

Comparing checksum to find if a file was changed is valid and you can also compare when file was last modified by using fs.stat

like image 97
Rayee Roded Avatar answered Oct 07 '22 01:10

Rayee Roded