Cloudflare Workers中如何实现Node.js的Buffer.from()功能?
Got it, let's break this down. The reason you're hitting that error is because Cloudflare Workers runs on a standard Web Runtime, not Node.js. Node's Buffer is a non-standard extension to JavaScript—Workers doesn't include it by default, but we can use native Web APIs to get the exact same behavior.
Here's how to rewrite your Node.js Buffer code for the Workers environment:
1. Replace Buffer.from(str) (UTF-8 string to bytes)
In Node, Buffer.from(str) encodes the string to UTF-8 bytes under the hood. The Web API equivalent is TextEncoder, which does exactly this and returns a Uint8Array (a standard JavaScript type that Buffer extends in Node, so they're mostly interchangeable for byte-related operations).
const str = "dasjkiodjsiodjpasiodfjodifjaspiofjsdioajfpasodfjsdioa"; // Replace Buffer.from(str) with this: const encoder = new TextEncoder(); const buff = encoder.encode(str); // Returns Uint8Array, works like Buffer for most use cases
2. Replace Buffer.from(str, 'hex') (Hex string to bytes)
There's no built-in Web API for converting a hex string directly to bytes, but we can write a simple helper function that mimics Node's behavior (including validation for invalid hex strings):
function hexToUint8Array(hexStr) { // Match Node's error behavior for uneven-length hex strings if (hexStr.length % 2 !== 0) { throw new Error('Hex string must have an even length'); } const bytes = new Uint8Array(hexStr.length / 2); for (let i = 0; i < hexStr.length; i += 2) { const byteValue = parseInt(hexStr.slice(i, i + 2), 16); if (isNaN(byteValue)) { throw new Error(`Invalid hex character at position ${i}`); } bytes[i / 2] = byteValue; } return bytes; } // Use it like you would Buffer.from(str, 'hex'): const buffHex = hexToUint8Array(str); // Throws if `str` isn't valid hex, just like Node's implementation
Bonus: If you need Buffer-specific methods (like .toString('hex'))
If you need to convert bytes back to a hex string (the reverse of Buffer.from(str, 'hex')), here's another helper function:
function uint8ArrayToHex(bytes) { return Array.from(bytes) .map(byte => byte.toString(16).padStart(2, '0')) .join(''); } // Equivalent to buff.toString('hex') in Node: const hexString = uint8ArrayToHex(buff);
Should you use a Buffer polyfill?
You could technically add a polyfill like @esbuild-plugins/node-globals-polyfill to get Node's Buffer in Workers, but this isn't recommended. Polyfills add unnecessary bundle size, and the native Web APIs are designed to be lightweight and perfect for Workers' serverless environment.
内容的提问来源于stack exchange,提问作者Dug




