Node 的 Buffer.from(string, "binary") 的 Deno 等价物是什么?
What is the Deno equivalent of Node's Buffer.from(string, "binary")?
我发现了类似的问题 ,但它缺少有关“二进制”编码的信息。 TextEncoder
(看起来)不是 Deno 中“二进制”的等价物。
这是一个例子:
Deno
const str = "ºRFl¶é(÷LõÎW0 Náò8ìÉPPv[=12=]";
const bytes = new TextEncoder().encode(str);
console.log(crypto.createHash("sha256").update(bytes).digest("hex"));
输出:65e16c433fdc795b29668dc1d189b79f2b809dc4623b03c0b9c551bd83d67069
节点
const str = "ºRFl¶é(÷LõÎW0 Náò8ìÉPPv[=13=]";
const buffer = Buffer.from(str, "binary");
console.log(crypto.createHash("sha256").update(buffer).digest("hex"));
节点输出:fb6d4a2f86e91b13fe2d5a6d2e6ebb9b6f66e18a733b68acbf9ac3c5e56571d0
Node 的(已弃用)binary
编码实际上是 latin-1
(ISO-8859-1)。
假设您的字符串不使用超出该范围的字符,您可以通过将单个字符转换为其 UTF-16 代码单元值来创建字节数组:
import { createHash } from "https://deno.land/std/hash/mod.ts";
const str = "ºRFl¶é(÷LõÎW0 Náò8ìÉPPv[=10=]";
const bytes = Uint8Array.from([...str].map(c => c.charCodeAt(0)));
console.log(createHash("sha256").update(bytes).toString());
根据需要输出:
fb6d4a2f86e91b13fe2d5a6d2e6ebb9b6f66e18a733b68acbf9ac3c5e56571d0
我发现了类似的问题 TextEncoder
(看起来)不是 Deno 中“二进制”的等价物。
这是一个例子:
Deno
const str = "ºRFl¶é(÷LõÎW0 Náò8ìÉPPv[=12=]";
const bytes = new TextEncoder().encode(str);
console.log(crypto.createHash("sha256").update(bytes).digest("hex"));
输出:65e16c433fdc795b29668dc1d189b79f2b809dc4623b03c0b9c551bd83d67069
节点
const str = "ºRFl¶é(÷LõÎW0 Náò8ìÉPPv[=13=]";
const buffer = Buffer.from(str, "binary");
console.log(crypto.createHash("sha256").update(buffer).digest("hex"));
节点输出:fb6d4a2f86e91b13fe2d5a6d2e6ebb9b6f66e18a733b68acbf9ac3c5e56571d0
Node 的(已弃用)binary
编码实际上是 latin-1
(ISO-8859-1)。
假设您的字符串不使用超出该范围的字符,您可以通过将单个字符转换为其 UTF-16 代码单元值来创建字节数组:
import { createHash } from "https://deno.land/std/hash/mod.ts";
const str = "ºRFl¶é(÷LõÎW0 Náò8ìÉPPv[=10=]";
const bytes = Uint8Array.from([...str].map(c => c.charCodeAt(0)));
console.log(createHash("sha256").update(bytes).toString());
根据需要输出:
fb6d4a2f86e91b13fe2d5a6d2e6ebb9b6f66e18a733b68acbf9ac3c5e56571d0