如何在Node JS中哈希下载流

时间:2019-10-14 05:46:51

标签: javascript node.js

我想知道如何使用节点js散列文件的下载流

因为我想在存储到mongo db之前对文件进行哈希处理以避免重复,所以我正在使用mongo grid fs。 https://github.com/aheckmann/gridfs-stream

下载文件

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

1 个答案:

答案 0 :(得分: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
    });
}