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
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.
You can use Node.js's Buffer API with Cloudflare Workers.
See https://developers.cloudflare.com/workers/runtime-apis/nodejs/ which explains that by adding compatibility_flags = [ "nodejs_compat" ] to your wrangler.toml you can use the following Node.js APIs:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With