stream - 如何在 Deno 中获取文件校验和?
问题描述
刚从 Deno 开始,我试图弄清楚如何计算二进制文件校验和。在我看来,问题不在于标准库的 hash 模块提供的方法,而在于文件流方法和/或提供 hash.update 方法的块的类型。我一直在尝试一些与文件打开和块类型相关的替代方案,但没有成功。一个简单的例子如下:
import {createHash} from "https://deno.land/std@0.80.0/hash/mod.ts";
const file= new File(["my_big_folder.tar.gz"], "./my_big_folder.tar.gz");
const iterator = file.stream() .getIterator();
const hash = createHash("md5");
for await( let chunk of iterator){
hash.update(chunk);
}
console.log(hash.toString()); //b35edd0be7acc21cae8490a17c545928
这段代码编译并运行没有错误,可惜结果与我运行node提供的crypto模块和linux coreutils提供的md5sum的功能不同。有什么建议吗?
节点代码:
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('md5');
const file = './my_big_folder.tar.gz';
const stream = fs.ReadStream(file);
stream.on('data', data=> { hash.update(data); });
stream.on('end', ()=> {
console.log(hash.digest('hex')); //c18f5eac67656328f7c4ec5d0ef5b96f
});
bash 中的结果相同:
$ md5sum ./my_big_folder.tar.gz
$ c18f5eac67656328f7c4ec5d0ef5b96f ./my_big_folder.tar.gz
在 Windows 10 上可以使用:
CertUtil -hashfile ./my_big_folder.tar.gz md5
解决方案
File API 不用于在 Deno 中读取文件,为此您需要使用 Deno.open API,然后将其转换为像这样的可迭代对象
import {createHash} from "https://deno.land/std@0.80.0/hash/mod.ts";
const hash = createHash("md5");
const file = await Deno.open(new URL(
"./BigFile.tar.gz",
import.meta.url, //This is needed cause JavaScript paths are relative to main script not current file
));
for await (const chunk of Deno.iter(file)) {
hash.update(chunk);
}
console.log(hash.toString());
Deno.close(file.rid);
推荐阅读
- python-3.x - 在 GCP 功能中使用 Flask 路由?
- keras - Keras 功能 API:将 CNN 模型与 RNN 结合起来查看图像序列
- python - 更快地关闭 tkinter 窗口(当有很多按钮时)
- c# - 合并两个列表并替换元素
- php - 更改 PHP 梨邮件中的电子邮件标题
- python - 为什么我的标签没有显示在 tkinter 中?
- python - Setuptools:使用源文件夹中的 setup.py 从“项目”导入
- javascript - 使用javascript在Adobe中根据大小删除空白页
- c - 在 C 中:头文件和编译 main 函数时遇到问题
- python - Python中的列表是否存在“无关”值