繁体   English   中英

Cloudflare Workers Buffer.from()

[英]Cloudflare Workers Buffer.from()

我对 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)

我将如何 go 在 Cloudflare Workers 中执行此操作,因为我收到ReferenceError: Buffer is not defined

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

let bytes = new TextEncoder().encode(str);

要将Uint8Array转换为十六进制,您可以使用 function ,例如:

function bytes2hex(bytes) {
  return Array.prototype.map.call(bytes,
      byte => ('0' + byte.toString(16)).slice(-2)).join('');
}

我不建议为此使用Buffer polyfill,因为它会使您的代码体积膨胀。 最好直接使用Uint8Array

一般来说,您应该能够在 Stack Overflow 上找到有关如何对Uint8Array进行常见操作的答案。

这是一个示例,说明如何在 Cloudflare 工作人员中创建“hello world”的 SHA-256 hash,只需使用全球可用的 WebCrypto 浏览器 API。 希望它能让您对它的工作原理有所了解!

export default {
  async fetch(request)
  {
    const myText = new TextEncoder().encode('Hello world!');
    const myDigest = await crypto.subtle.digest({ name: 'SHA-256' }, myText);
    const hashArray = Array.from(new Uint8Array(myDigest));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
    return new Response(hashHex, {status: 200});
  }
}

更多信息: https://developers.cloudflare.com/workers/runtime-apis/web-crypto/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM