简体   繁体   English

Cloudflare Workers Buffer.from()

[英]Cloudflare Workers Buffer.from()

I am not that familiar with how Buffers and all that work.我对 Buffers 和所有这些工作的方式不太熟悉。

In node I can do在节点我可以做

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)

How would I go about doing this in Cloudflare Workers, because I get ReferenceError: Buffer is not defined我将如何 go 在 Cloudflare Workers 中执行此操作,因为我收到ReferenceError: Buffer is not defined

Buffer is a Node API. Buffer是一个节点 API。 Cloudflare Workers is based on web platform APIs instead, like what you'd find in browsers. Cloudflare Workers 基于 web 平台 API,就像您在浏览器中找到的一样。 The web platform alternative to Buffer is Uint8Array . Buffer的 web 平台替代品是Uint8Array You can use the TextEncoder and TextDecoder APIs to convert between Uint8Array s with UTF-8 encoding and text strings.您可以使用TextEncoderTextDecoder API 在使用 UTF-8 编码的Uint8Array和文本字符串之间进行转换。

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

To convert a Uint8Array to hex, you can use a function like:要将Uint8Array转换为十六进制,您可以使用 function ,例如:

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

I do not recommend using a Buffer polyfill for this as it'll bloat your code size.我不建议为此使用Buffer polyfill,因为它会使您的代码体积膨胀。 It's better to use Uint8Array directly.最好直接使用Uint8Array

In general you should be able to find answers about how to do common operations on Uint8Array on Stack Overflow.一般来说,您应该能够在 Stack Overflow 上找到有关如何对Uint8Array进行常见操作的答案。

Here's an example of how to create a SHA-256 hash of "hello world" in Cloudflare workers, just using the globally available WebCrypto browser API.这是一个示例,说明如何在 Cloudflare 工作人员中创建“hello world”的 SHA-256 hash,只需使用全球可用的 WebCrypto 浏览器 API。 Hope it gives you some insight into how this works!希望它能让您对它的工作原理有所了解!

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});
  }
}

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

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

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