0

I would like to get the md5 hash of a file in nodejs, but the hash i'm getting is different from the hash i can get directly from the terminal.

In nodejs, I'm doing this (from here)

var fd = fs.createReadStream('path/to/my/file');
var hash = crypto.createHash('md5');
hash.setEncoding('hex');

fd.on('end', function() {
    hash.end();
    console.log(hash.read()); // the desired sha1sum
});

fd.pipe(hash);

and the output is d41d8cd98f00b204e9800998ecf8427e

And in my terminal I do:

md5sum path/to/my/file

and the ouput is f6ef86836065f2370ebd9b1caadce3b4

Do you have any idea about why ?

Thanks

EDIT

Here is my code:

//Download file
var firmware = fs.createWriteStream(desiredFirmwareProperties.fwName);
var r = https.get(desiredFirmwareProperties.fwURI, function(response) {
    response.pipe(firmware);
});

//Checksum
var fd = fs.createReadStream(desiredFirmwareProperties.fwName);
var hash = crypto.createHash(desiredFirmwareProperties.fwChecksumAlgo);     
hash.setEncoding('hex');
fd.on('end', function() {
    hash.end();
    console.log(desiredFirmwareProperties.fwChecksum);
    console.log(hash.read());
});
fd.pipe(hash);

iAmoric
  • 1,787
  • 3
  • 31
  • 64

1 Answers1

0

I got it, it's an asynchronous procedure, you tried to read the file before the download finished

place the checksum procedure in 'close' event:

firmware.on('close', () => {
  <checksum here>
})
np42
  • 847
  • 7
  • 13