【问题标题】:What is the Deno equivalent of Node's Buffer.from(string, "binary")?Node 的 Buffer.from(string, "binary") 的 Deno 等价物是什么?
【发布时间】:2021-09-16 11:55:06
【问题描述】:

我发现了类似的问题here,但它缺少有关“二进制”编码的信息。 TextEncoder(似乎)不是 Deno 中“二进制”的等价物。

这是一个例子:

德诺

const str = "ºRFl¶é(÷LõÎW0 Náò8ìÉPPv\0";
const bytes = new TextEncoder().encode(str);
console.log(crypto.createHash("sha256").update(bytes).digest("hex"));

输出:65e16c433fdc795b29668dc1d189b79f2b809dc4623b03c0b9c551bd83d67069

节点

const str = "ºRFl¶é(÷LõÎW0 Náò8ìÉPPv\0";
const buffer = Buffer.from(str, "binary");
console.log(crypto.createHash("sha256").update(buffer).digest("hex"));

节点输出:fb6d4a2f86e91b13fe2d5a6d2e6ebb9b6f66e18a733b68acbf9ac3c5e56571d0

【问题讨论】:

    标签: javascript node.js deno


    【解决方案1】:

    节点的(已弃用)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\0";
    const bytes = Uint8Array.from([...str].map(c => c.charCodeAt(0)));
    
    console.log(createHash("sha256").update(bytes).toString());
    

    根据需要输出:

    fb6d4a2f86e91b13fe2d5a6d2e6ebb9b6f66e18a733b68acbf9ac3c5e56571d0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2017-10-29
      • 1970-01-01
      • 2015-10-17
      相关资源
      最近更新 更多