# node:buffer

O módulo `node:buffer` fornece `Buffer`, a classe do Node.js que armazena dados binários brutos como uma sequência de bytes. Use-o para converter texto entre codificações como `hex` e `base64`, para combinar e fatiar dados binários e para ler o corpo de uma requisição ou um stream como bytes. No Azion Runtime, `Buffer` também é um global: o global e a classe que você importa de `node:buffer` são o mesmo objeto, e todo buffer é um `Uint8Array`.

---

## Exemplos

Cada exemplo é uma function completa que importa `Buffer` de `node:buffer`. A resposta abaixo de cada exemplo é a que uma function com deploy feito retorna.

### Operações básicas com buffer

Esta function cria um buffer a partir de uma string, exibe o buffer em duas codificações e sobrescreve parte dele:

```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;
```

A function responde com o texto sobrescrito:

```text
Hello World
```

### Conversões de codificação de buffer

Esta function converte uma string para três codificações de transmissão de dados e depois decodifica a forma `base64` de volta para texto:

```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;
```

A function responde com cada codificação da string:

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

No Azion Runtime, a saída `base64url` mantém o preenchimento `=`, como mostra o valor `base64url`, e `Buffer.isEncoding("base64url")` retorna `false`.

### Concatenação e fatiamento de buffer

Esta function combina três buffers em um só e depois extrai e copia uma parte do resultado:

```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;
```

A function responde com o buffer combinado e as duas partes extraídas:

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

### Processamento de dados binários

Esta function lê o corpo da requisição como um buffer, procura nele uma sequência de bytes e, em seguida, compara e aloca 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;
```

Para uma requisição `POST` cujo corpo é `Hello Azion Runtime`, a function responde com o tamanho do corpo, o primeiro byte dele e a posição de `Azion`:

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

### Serialização JSON com buffers

Esta function converte um objeto em um buffer JSON, usa o tamanho do buffer na resposta e define `Content-Length` a partir dele:

```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;
```

A function responde com o objeto e o tamanho do buffer, com `Content-Length` definido como `78`:

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

---

## APIs suportadas

A tabela lista o status de cada API de `node:buffer` no Azion Runtime:

| API                         | Status                                      |
| --------------------------- | ------------------------------------------- |
| `Buffer.alloc()`            | 🟢 Com suporte                              |
| `Buffer.allocUnsafe()`      | 🟢 Com suporte                              |
| `Buffer.byteLength()`       | 🟢 Com suporte                              |
| `Buffer.compare()`          | 🟢 Com suporte                              |
| `Buffer.concat()`           | 🟢 Com suporte                              |
| `Buffer.from()`             | 🟢 Com suporte                              |
| `Buffer.isBuffer()`         | 🟢 Com suporte                              |
| `Buffer.isEncoding()`       | 🟢 Com suporte                              |
| `buf.compare()`             | 🟢 Com suporte                              |
| `buf.copy()`                | 🟢 Com suporte                              |
| `buf.equals()`              | 🟢 Com suporte                              |
| `buf.fill()`                | 🟢 Com suporte                              |
| `buf.indexOf()`             | 🟢 Com suporte                              |
| `buf.includes()`            | 🟢 Com suporte                              |
| `buf.lastIndexOf()`         | 🟢 Com suporte                              |
| `buf.length`                | 🟢 Com suporte                              |
| `buf.readInt*()`            | 🟡 Suporte parcial                          |
| `buf.subarray()`            | 🟢 Com suporte                              |
| `buf.slice()`               | 🟡 Com suporte (obsoleta, use `subarray()`) |
| `buf.toString()`            | 🟢 Com suporte                              |
| `buf.write()`               | 🟢 Com suporte                              |
| `buf.writeInt*()`           | 🟡 Suporte parcial                          |
| `buffer.isAscii()`          | 🔴 Sem suporte                              |
| `buffer.isUtf8()`           | 🔴 Sem suporte                              |
| `buffer.resolveObjectURL()` | 🔴 Sem suporte                              |
| `buffer.transcode()`        | 🔴 Sem suporte                              |

As APIs marcadas como 🟡 Suporte parcial têm funcionalidade limitada em comparação com a implementação completa do Node.js. Entre elas, `writeUInt32BE()`, `readUInt32BE()`, `writeInt16LE()` e `readInt16LE()` retornam os valores gravados, e `readBigUInt64BE()` está disponível. As funções de nível de módulo `buffer.isAscii()`, `buffer.isUtf8()`, `buffer.resolveObjectURL()` e `buffer.transcode()` não têm suporte. O Node.js marca `buf.slice()` como obsoleta a partir da v17.5.0; use `buf.subarray()` em vez dela.

---

## Recursos relacionados

- [APIs do Node.js](/pt-br/documentacao/devtools/runtime/node.md): O status de cada módulo do Node.js no Azion Runtime, incluindo `buffer`.
- [Use APIs do Node.js com polyfills](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/functions-e-runtime/use-polyfills.md): Como o build transforma imports `node:` em código que é executado no Azion Runtime.
- [Encoding](/pt-br/documentacao/devtools/runtime/api-reference/encoding.md): A alternativa da Web API para converter entre texto e bytes.
- [Documentação de buffer do Node.js](https://nodejs.org/api/buffer.html): A referência completa do Node.js para cada API de `node:buffer` da tabela.
