从问题中引用的片段中:
【Hash类】是一个可读可写的流。写入的数据用于计算哈希。一旦流的可写端结束,使用 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();
如果要获取文件的哈希,最好的方法是从文件中创建一个 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);