Obtaining the hash of a file using the stream capabilities of crypto module (ie: without hash.update and hash.digest)

后端 未结 6 937
醉酒成梦
醉酒成梦 2020-12-04 15:25

The crypto module of node.js (at the time of this writing at least) is not still deemed stable and so the API may change. In fact, the methods that everyone in the internet

6条回答
  •  一整个雨季
    2020-12-04 16:00

    An ES6 version returning a Promise for the hash digest:

    function checksumFile(hashName, path) {
      return new Promise((resolve, reject) => {
        const hash = crypto.createHash(hashName);
        const stream = fs.createReadStream(path);
        stream.on('error', err => reject(err));
        stream.on('data', chunk => hash.update(chunk));
        stream.on('end', () => resolve(hash.digest('hex')));
      });
    }
    

提交回复
热议问题