Skip to main content
在 Bun 中,推荐使用 Uint8Array.prototype.toBase64()Uint8Array.fromBase64() 来编码和解码 base64 数据。这些 API 直接操作字节,因此比旧的 btoa()atob() 全局函数更适合处理二进制数据。
对于字符串,使用 TextEncoderTextDecoder 转换为 UTF-8 字节。
Node.js 的 Buffer 继承自 Uint8Array,因此可以使用 toBase64() 编码缓冲区,并传递给接受 Uint8Array 的 API。Buffer 还提供 Node.js 兼容的 base64 解码:Buffer.from(encoded, "base64")
较旧的 btoa()atob() API 仍然可用以保持兼容性,但它们操作的是二进制字符串而不是字节数组。在新代码中应避免使用,特别是在处理任意二进制数据或非 ASCII 文本时。

参见 Web API