執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

編碼和解碼 base64 資料

在 Bun 中編碼和解碼 base64 資料時,優先使用 Uint8Array.prototype.toBase64() 和 Uint8Array.fromBase64()。這些 API 直接處理位元組,因此相比舊版的 btoa() 和 atob() 全域性函式,它們更適合處理二進位制資料。

TypeScript
const bytes = new Uint8Array([98, 117, 110]);
const encoded = bytes.toBase64(); // => "YnVu"

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

對於字串,使用 TextEncoder 和 TextDecoder 在 UTF-8 位元組之間進行轉換。

TypeScript
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 還通過 Buffer.from(encoded, "base64") 提供與 Node.js 相容的 base64 解碼功能。

TypeScript
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"

請參閱 Web API。