如何在 Deno 中获取文件校验和?

mre*_*mre 4 checksum stream md5sum sha1sum deno

刚从 Deno 开始,我试图弄清楚如何计算二进制文件校验和。在我看来,问题不在于标准库的哈希模块提供的方法,而在于文件流方法和/或提供 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
Run Code Online (Sandbox Code Playgroud)

这段代码编译并运行没有错误,遗憾的是结果与我运行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
});

Run Code Online (Sandbox Code Playgroud)

bash 中的结果相同:

$ md5sum ./my_big_folder.tar.gz
$ c18f5eac67656328f7c4ec5d0ef5b96f ./my_big_folder.tar.gz
Run Code Online (Sandbox Code Playgroud)

在 Windows 10 上可以使用:

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
Run Code Online (Sandbox Code Playgroud)

Ste*_*ero 5

文件 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);
Run Code Online (Sandbox Code Playgroud)