javascriptbuffercloudflare-workers

Cloudflare Workers Buffer.from()


I am not that familiar with how Buffers and all that work.

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


Solution

  • Buffer is a Node API. Cloudflare Workers is based on web platform APIs instead, like what you'd find in browsers. The web platform alternative to Buffer is Uint8Array. You can use the TextEncoder and TextDecoder APIs to convert between Uint8Arrays with UTF-8 encoding and text strings.

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

    To convert a Uint8Array to hex, you can use a function like:

    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. It's better to use Uint8Array directly.

    In general you should be able to find answers about how to do common operations on Uint8Array on Stack Overflow.