# node:buffer

The `node:buffer` module provides `Buffer`, the Node.js class that holds raw binary data as a sequence of bytes. Use it to convert text between encodings such as `hex` and `base64`, to combine and slice binary data, and to read a request body or a stream as bytes. In Azion Runtime, `Buffer` is also a global: the global and the class you import from `node:buffer` are the same object, and every buffer is a `Uint8Array`.

---

## Examples

Each example is a complete function that imports `Buffer` from `node:buffer`. The response below each example is the one a deployed function returns.

### Basic buffer operations

This function creates a buffer from a string, prints it in two encodings, and overwrites part of it:

```javascript
/**
 * An example of using the Node.js Buffer API in an Azion Function.
 * Support:
 * - Partial support
 * @module runtime-apis/nodejs/buffer/main
 * @example
 * // Build and run with the Azion CLI:
 * azion build
 * azion dev
 */
import { Buffer } from "node:buffer";

/**
 * Example of using the Node.js Buffer API
 * Writes `string` to `buf` at `offset` according to the character encoding in `encoding`. The `length` parameter is the number of bytes to write. If `buf` did
 * not contain enough space to fit the entire string, only part of `string` will be
 * written. However, partially encoded characters will not be written.
 * @param {*} event
 * @returns {Promise<Response>}
 */
const main = async (event) => {
  const helloBuffer = Buffer.from("Hello Edge!", "utf8");
  console.log(helloBuffer.toString("hex"));
  // 48656c6c6f204564676521
  console.log(helloBuffer.toString("base64"));
  // SGVsbG8gRWRnZSE=

  helloBuffer.write("World", 6, 5, "utf8");
  console.log(helloBuffer.toString());
  // Hello World
  return new Response(helloBuffer.toString(), { status: 200 });
};
export default main;
```

The function responds with the overwritten text:

```text
Hello World
```

### Buffer encoding conversions

This function converts one string to three encodings for data transmission, then decodes the `base64` form back to text:

```javascript
import { Buffer } from "node:buffer";

const main = async (event) => {
  // Create buffer from string
  const textBuffer = Buffer.from("Azion Runtime", "utf8");

  // Convert to different encodings
  const hexEncoded = textBuffer.toString("hex");
  const base64Encoded = textBuffer.toString("base64");
  const base64urlEncoded = textBuffer.toString("base64url");

  console.log("Hex:", hexEncoded);
  console.log("Base64:", base64Encoded);
  console.log("Base64URL:", base64urlEncoded);

  // Decode back from base64
  const decoded = Buffer.from(base64Encoded, "base64").toString("utf8");
  console.log("Decoded:", decoded);

  // Create JSON response with all encodings
  return new Response(JSON.stringify({
    original: "Azion Runtime",
    hex: hexEncoded,
    base64: base64Encoded,
    base64url: base64urlEncoded,
    decoded: decoded
  }), {
    headers: { "Content-Type": "application/json" }
  });
};

export default main;
```

The function responds with each encoding of the string:

```json
{"original":"Azion Runtime","hex":"417a696f6e2052756e74696d65","base64":"QXppb24gUnVudGltZQ==","base64url":"QXppb24gUnVudGltZQ==","decoded":"Azion Runtime"}
```

In Azion Runtime, `base64url` output keeps the `=` padding, as the `base64url` value shows, and `Buffer.isEncoding("base64url")` returns `false`.

### Buffer concatenation and slicing

This function combines three buffers into one, then extracts and copies a portion of the result:

```javascript
import { Buffer } from "node:buffer";

const main = async (event) => {
  // Create multiple buffers
  const header = Buffer.from("HEADER:", "utf8");
  const content = Buffer.from("Hello World", "utf8");
  const footer = Buffer.from(":END", "utf8");

  // Concatenate buffers
  const combined = Buffer.concat([header, content, footer]);
  console.log("Combined:", combined.toString());
  // Combined: HEADER:Hello World:END

  // Use subarray() to extract content (preferred over deprecated slice())
  const contentOnly = combined.subarray(7, 18);
  console.log("Extracted:", contentOnly.toString());
  // Extracted: Hello World

  // Get buffer length
  console.log("Total length:", combined.length);
  // Total length: 22

  // Copy portion to another buffer
  const copy = Buffer.alloc(11);
  combined.copy(copy, 0, 7, 18);
  console.log("Copied:", copy.toString());
  // Copied: Hello World

  return new Response(JSON.stringify({
    combined: combined.toString(),
    extracted: contentOnly.toString(),
    copied: copy.toString()
  }), {
    headers: { "Content-Type": "application/json" }
  });
};

export default main;
```

The function responds with the combined buffer and the two extracted portions:

```json
{"combined":"HEADER:Hello World:END","extracted":"Hello World","copied":"Hello World"}
```

### Binary data processing

This function reads the request body as a buffer, searches it for a byte sequence, and compares and allocates buffers:

```javascript
import { Buffer } from "node:buffer";

const main = async (event) => {
  // Get request body
  const request = event.request;
  const arrayBuffer = await request.arrayBuffer();

  // Handle empty request body
  if (!arrayBuffer.byteLength) {
    return new Response(JSON.stringify({
      error: "Empty request body",
      length: 0
    }), {
      status: 400,
      headers: { "Content-Type": "application/json" }
    });
  }

  const dataBuffer = Buffer.from(arrayBuffer);

  // Check buffer properties
  console.log("Buffer length:", dataBuffer.length);
  console.log("First byte:", dataBuffer[0]);

  // Find byte sequence
  const searchBuffer = Buffer.from("Azion", "utf8");
  const index = dataBuffer.indexOf(searchBuffer);
  console.log("Found 'Azion' at index:", index);

  // Compare buffers
  const buf1 = Buffer.from("test");
  const buf2 = Buffer.from("test");
  console.log("Buffers equal:", buf1.equals(buf2));

  // Create buffer with specific size
  const allocated = Buffer.alloc(256);
  allocated.write("Allocated buffer example", 0, "utf8");
  console.log("Allocated:", allocated.toString("utf8", 0, 24));

  return new Response(JSON.stringify({
    length: dataBuffer.length,
    firstByte: dataBuffer[0],
    foundAtIndex: index
  }), {
    headers: { "Content-Type": "application/json" }
  });
};

export default main;
```

For a `POST` request whose body is `Hello Azion Runtime`, the function responds with the body length, its first byte, and the position of `Azion`:

```json
{"length":19,"firstByte":72,"foundAtIndex":6}
```

### JSON serialization with buffers

This function converts an object to a JSON buffer, uses the buffer size in the response, and sets `Content-Length` from it:

```javascript
import { Buffer } from "node:buffer";

const main = async (event) => {
  // Create object with data
  const data = {
    id: 12345,
    name: "Azion Function",
    timestamp: Date.now()
  };

  // Convert to JSON string and then to buffer
  const jsonString = JSON.stringify(data);
  const jsonBuffer = Buffer.from(jsonString, "utf8");

  // Calculate size for headers
  const contentLength = jsonBuffer.length;

  // Convert back to object
  const parsed = JSON.parse(jsonBuffer.toString("utf8"));

  console.log("JSON buffer size:", contentLength, "bytes");
  console.log("Parsed object:", parsed);

  // Create response buffer with metadata
  const responseData = {
    ...parsed,
    bufferSize: contentLength
  };
  const responseBuffer = Buffer.from(JSON.stringify(responseData), "utf8");

  return new Response(responseBuffer, {
    headers: {
      "Content-Type": "application/json",
      "Content-Length": responseBuffer.length.toString()
    }
  });
};

export default main;
```

The function responds with the object and its buffer size, with `Content-Length` set to `78`:

```json
{"id":12345,"name":"Azion Function","timestamp":1767268800000,"bufferSize":62}
```

---

## Supported APIs

The table lists the status of each `node:buffer` API in Azion Runtime:

| API                         | Status                                      |
| --------------------------- | ------------------------------------------- |
| `Buffer.alloc()`            | 🟢 Supported                                |
| `Buffer.allocUnsafe()`      | 🟢 Supported                                |
| `Buffer.byteLength()`       | 🟢 Supported                                |
| `Buffer.compare()`          | 🟢 Supported                                |
| `Buffer.concat()`           | 🟢 Supported                                |
| `Buffer.from()`             | 🟢 Supported                                |
| `Buffer.isBuffer()`         | 🟢 Supported                                |
| `Buffer.isEncoding()`       | 🟢 Supported                                |
| `buf.compare()`             | 🟢 Supported                                |
| `buf.copy()`                | 🟢 Supported                                |
| `buf.equals()`              | 🟢 Supported                                |
| `buf.fill()`                | 🟢 Supported                                |
| `buf.indexOf()`             | 🟢 Supported                                |
| `buf.includes()`            | 🟢 Supported                                |
| `buf.lastIndexOf()`         | 🟢 Supported                                |
| `buf.length`                | 🟢 Supported                                |
| `buf.readInt*()`            | 🟡 Partially supported                      |
| `buf.subarray()`            | 🟢 Supported                                |
| `buf.slice()`               | 🟡 Supported (deprecated, use `subarray()`) |
| `buf.toString()`            | 🟢 Supported                                |
| `buf.write()`               | 🟢 Supported                                |
| `buf.writeInt*()`           | 🟡 Partially supported                      |
| `buffer.isAscii()`          | 🔴 Not supported                            |
| `buffer.isUtf8()`           | 🔴 Not supported                            |
| `buffer.resolveObjectURL()` | 🔴 Not supported                            |
| `buffer.transcode()`        | 🔴 Not supported                            |

APIs marked 🟡 Partially supported have limited functionality compared to the full Node.js implementation. Among them, `writeUInt32BE()`, `readUInt32BE()`, `writeInt16LE()`, and `readInt16LE()` return the values written, and `readBigUInt64BE()` is available. The module-level functions `buffer.isAscii()`, `buffer.isUtf8()`, `buffer.resolveObjectURL()`, and `buffer.transcode()` are not supported. Node.js deprecates `buf.slice()` from v17.5.0; use `buf.subarray()` instead.

---

## Related resources

- [Node.js APIs](/en/documentation/devtools/runtime/node.md): The status of every Node.js module in Azion Runtime, `buffer` included.
- [Use Node.js APIs through polyfills](/en/documentation/guides/application-development/functions-and-runtime/use-polyfills.md): How the build turns `node:` imports into code that runs in Azion Runtime.
- [Encoding](/en/documentation/devtools/runtime/api-reference/encoding.md): The Web API alternative for converting between text and bytes.
- [Node.js buffer documentation](https://nodejs.org/api/buffer.html): The full Node.js reference for every `node:buffer` API in the table.
