> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 编码和解码 base64 数据

在 Bun 中，推荐使用 [`Uint8Array.prototype.toBase64()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/toBase64) 和 [`Uint8Array.fromBase64()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/fromBase64) 来编码和解码 base64 数据。这些 API 直接操作字节，因此比旧的 `btoa()` 和 `atob()` 全局函数更适合处理二进制数据。

```ts theme={null}
const bytes = new Uint8Array([98, 117, 110]);
const encoded = bytes.toBase64(); // => "YnVu"

const decoded = Uint8Array.fromBase64(encoded);
// => Uint8Array(3) [ 98, 117, 110 ]
```

对于字符串，使用 [`TextEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder) 和 [`TextDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder) 转换为 UTF-8 字节。

```ts theme={null}
const bytes = new TextEncoder().encode("hello world");
const encoded = bytes.toBase64(); // => "aGVsbG8gd29ybGQ="

const decoded = Uint8Array.fromBase64(encoded);
const text = new TextDecoder().decode(decoded); // => "hello world"
```

Node.js 的 `Buffer` 继承自 `Uint8Array`，因此可以使用 `toBase64()` 编码缓冲区，并传递给接受 `Uint8Array` 的 API。`Buffer` 还提供 Node.js 兼容的 base64 解码：`Buffer.from(encoded, "base64")`。

```ts theme={null}
const encoded = Buffer.from("hello world").toBase64();
// => "aGVsbG8gd29ybGQ="

const bytes = Buffer.from(encoded, "base64");
bytes instanceof Uint8Array; // => true

const text = bytes.toString("utf8");
// => "hello world"
```

<Warning>
  较旧的 [`btoa()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa) 和 [`atob()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/atob) API 仍然可用以保持兼容性，但它们操作的是二进制字符串而不是字节数组。在新代码中应避免使用，特别是在处理任意二进制数据或非 ASCII 文本时。

  ```ts theme={null}
  const encoded = btoa("bun"); // => "YnVu"
  const decoded = atob(encoded); // => "bun"
  ```
</Warning>

***

参见 [Web API](/runtime/web-apis)。
