To enable built-in Node.js APIs and polyfills, add the nodejs_compat compatibility flag to yourWrangler configuration file. This also enables nodejs_compat_v2 as long as your compatibility date is 2024-09-23 or later.Learn more about the Node.js compatibility flag and v2.
TheBuffer ↗ API in Node.js is one of the most commonly used Node.js APIs for manipulating binary data. EveryBuffer instance extends from the standardUint8Array ↗ class, but adds a range of unique capabilities such as built-in base64 and hex encoding/decoding, byte-order manipulation, and encoding-aware substring searching.
import{Buffer} from"node:buffer";constbuf=Buffer.from("hello world","utf8");console.log(buf.toString("hex"));// Prints: 68656c6c6f20776f726c64console.log(buf.toString("base64"));// Prints: aGVsbG8gd29ybGQ=A Buffer extends fromUint8Array. Therefore, it can be used in any Workers API that currently acceptsUint8Array, such as creating a new Response:
constresponse=newResponse(Buffer.from("hello world"));You can also use theBuffer API when interacting with streams:
constwritable=getWritableStreamSomehow();constwriter=writable.getWriter();writer.write(Buffer.from("hello world"));One key difference between the Workers implementation ofBuffer and the Node.jsimplementation is that some methods of creating aBuffer in Node.js will allocatethose from a global memory pool as a performance optimization. The Workers implementationdoes not use a memory pool and allBuffer instances are allocated independently.
Further, in Node.js it is possible to allocate aBuffer with uninitialized memoryusing theBuffer.allocUnsafe() method. This is not supported in Workers andBufferinstances are always initialized so that theBuffer is always filledwith null bytes (0x00) when allocated.
Refer to theNode.js documentation forBuffer ↗ for more information.