Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronous hashing function for files

I have a function which generates a checksum for a given path

function getHash(path) {
     var fs = require('fs');
     var crypto = require('crypto');

     var fd = fs.createReadStream(path);
     var hash = crypto.createHash('sha1');
     hash.setEncoding('hex');

     fd.on('end', function () {
        hash.end();
        // *** Here is my problem ***
        console.log(hash.read()); 
     });

     fd.pipe(hash);
  };

I want to call the calcNewHash function so that it returns the hash, the problem is, that I haven't found an asynchronous version of this, maybe some one can help.

Just add a return statement doesn't work, because the function is in a Listener

Later I want to add the checksum to an object, so I could give the reference to it as parameter, but this still does not change that this is ansynchronous ...

like image 722
Ba5t14n Avatar asked Dec 31 '25 21:12

Ba5t14n


1 Answers

I know this is old but it is in the top results when searching for something along these lines. So for those that land here looking for a solution to this, here you go: (note that this only works well if you know the file is small. Otherwise for larger files refer to the answer provided by Dieterg)

const fs = require('fs');
const crypto = require('crypto');

function fileHashSync(filePath){
    var fileData;

    try{ fileData = fs.readFileSync(filePath, 'utf8'); }

    catch(err){
        if(err.code === 'ENOENT') return console.error('File does not exist. Error: ', err);

        return console.error('Error: ', err);
    }

    return crypto.createHash('sha1').update(fileData, 'utf8').digest('hex');
}
like image 55
justFatLard Avatar answered Jan 03 '26 09:01

justFatLard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!