簡體   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