使用encryption模块的streamfunction获取文件的散列(即:没有hash.update和hash.digest)

node.js的crypto模块(至less在写这篇文章的时候)仍然不被认为是稳定的,所以API可能会改变。 事实上,互联网上每个人用来获取文件的散列(md5,sha1,…)的方法都被认为是遗留的(从Hash类的文档中)(注意:我的重点):

类:哈希

用于创build数据散列摘要的类。

这是一个可读写的stream。 写入的数据用于计算散列。 一旦stream的可写端被结束,使用read()方法来获得计算的散列摘要。 传统的更新和摘要方法也被支持。

由crypto.createHash返回。

尽pipehash.updatehash.digest被认为是遗留的,但是在引用片段上方显示的示例正在使用它们。

在不使用这些遗留方法的情况下获取哈希的正确方法是什么?

从问题中引用的片段:

[哈希类]它是一个可读写的stream。 写入的数据用于计算散列。 一旦stream的可写端被结束,使用read()方法来获得计算的散列摘要。

所以你需要散列一些文本是:

 var crypto = require('crypto'); // change to 'md5' if you want an MD5 hash var hash = crypto.createHash('sha1'); // change to 'binary' if you want a binary hash. hash.setEncoding('hex'); // the text that you want to hash hash.write('hello world'); // very important! You cannot read from the stream until you have called end() hash.end(); // and now you get the resulting hash var sha1sum = hash.read(); 

如果你想得到一个文件的散列,最好的方法是从文件中创build一个ReadStream,并将其传递给散列:

 var fs = require('fs'); var crypto = require('crypto'); // the file you want to get the hash var fd = fs.createReadStream('/some/file/name.txt'); var hash = crypto.createHash('sha1'); hash.setEncoding('hex'); fd.on('end', function() { hash.end(); console.log(hash.read()); // the desired sha1sum }); // read all file and pipe it (write it) to the hash object fd.pipe(hash); 

Carlos的答案短版:

 var fs = require('fs') var crypto = require('crypto') fs.createReadStream('/some/file/name.txt'). pipe(crypto.createHash('sha1').setEncoding('hex')). on('finish', function () { console.log(this.read()) //the hash }) 

为散列摘要返回一个承诺的ES6版本:

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