gpt4 book ai didi

javascript - Cloudflare Workers Buffer.from()

转载 作者:行者123 更新时间:2023-12-05 00:36:25 28 4
gpt4 key购买 nike

我对 Buffers 和所有这些工作的方式不是很熟悉。
在节点我可以做

const str = "dasjkiodjsiodjpasiodfjodifjaspiofjsdioajfpasodfjsdioa";
let buff = Buffer.from(str); // <Buffer 64 61 73 6a 6b 6 etc...
let buffHex = Buffer.from(str, 'hex');

console.log(buff)
我将如何在 Cloudflare Workers 中执行此操作,因为我得到 ReferenceError: Buffer is not defined

最佳答案

Buffer是一个节点 API。 Cloudflare Workers 是基于 Web 平台 API,就像您在浏览器中找到的一样。 Buffer 的网络平台替代品是 Uint8Array .您可以使用 TextEncoderTextDecoderUint8Array 之间转换的 API s 带有 UTF-8 编码和文本字符串。

let bytes = new TextEncoder().encode(str);
转换 Uint8Array到十六进制,您可以使用如下函数:
function bytes2hex(bytes) {
return Array.prototype.map.call(bytes,
byte => ('0' + byte.toString(16)).slice(-2)).join('');
}
我不建议使用 Buffer polyfill 为此,因为它会膨胀你的代码大小。最好使用 Uint8Array直接地。
一般来说,您应该能够在 Uint8Array 上找到有关如何进行常见操作的答案。关于堆栈溢出。

关于javascript - Cloudflare Workers Buffer.from(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69373818/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com