node 的crypto个模块.js(至少在 compose 本文时)仍被认为不稳定,因此API可能会发生变化.事实上,互联网上每个人用来获取散列的方法(md5、sha1等)一个文件的副本被认为是遗产(来自Hash class的文档)(注:强调我的):

类别:散列

用于创建数据哈希摘要的类.

它是一个既可读又可写的流.书面数据是

通过加密返回.createHash.

尽管hash.updatehash.digest被认为是遗留的,但引用的代码段上方显示的示例正在使用它们.

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

推荐答案

从问题中引用的片段中:

[哈希类]它是一个可读写的流.书面数据是

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

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

Node.js相关问答推荐

Spotify Auth访问令牌给出错误代码400

Sequelize-测试使用虚拟场更新模型

Sequelize、postgres和posgis:在n°;公里

如何在 ElectronJS 中播放音频文件

Socket.io 未将用户加入给定房间

try 使用 pdf.js 时 pdf.getPage 不是函数

AWS ECS 服务发现 Cors 问题?

等待不在 Express.js 中处理 res.app.render

使用 fs.createWriteStream 将数据写入 bigquery (node.js) 时出现模式错误

无法使用 node 预签名 url 从 React 将图像文件上传到 s3

如何避免在 mongodb 聚合中查找重复结果?

如何调用同名的两个函数?

如果 express.js (node.js) http 请求在完成之前关闭会发生什么?

如何在客户端使用 node.js 模块系统

如何监控 node.js 上的网络,类似于 chrome/firefox 开发者工具?

已安装全局 NPM 包但未找到命令

Express.js:没有这样的文件或目录

从 zip 文件在 AWS 中创建 lambda 函数

NodeJS 中的 HTTPS 请求

NodeJS:如何调试检测到 EventEmitter 内存泄漏.添加了 11 个侦听器