0

I want to know how to hash the download stream of a file using node js

Because I wanna hash the file before I store in to mongo db in order to avoid duplicates , I am using mongo grid fs by the way. https://github.com/aheckmann/gridfs-stream

downloading file

var download = function (url, dest, callback) {

                request.get(url)
                    .on('error', function (err) { console.log(err) })
                    .pipe(fs.createWriteStream(dest))
                    .on('close', callback);

            };

            final_list.forEach(function (str) {
                var filename = str.split('/').pop();

                console.log('Downloading ' + filename);

                download(str, filename, function () { console.log('Finished Downloading' + "" + filename) });
            });
Community
  • 1
  • 1
Jhon Caylog
  • 483
  • 8
  • 24

1 Answers1

1

function getHash(dest, filename) {
  let crypto = require('crypto');
  let hash = crypto.createHash('sha256').setEncoding('hex');
  let fileHash = "";
  let filePath = `${dest}/${filename}`
  fs.createReadStream(filePath)
    .pipe(hash)
    .on('finish', function() {
      fileHash = hash.read();
      console.log(`Filehash calculated for ${filename} is ${fileHash}.`);
      // insert into mongo db here
    });
}
Vikash_Singh
  • 1,856
  • 2
  • 14
  • 27