JavaScript atob() 和 btoa() 函數
JavaScript 內建 Base64 編碼和解碼函數的快速參考指南。
                    
                    |
                    
                
            btoa() - 編碼為 Base64
`btoa()` 函數從二進位資料建立 Base64 編碼的 ASCII 字串。
// 基本用法
const encoded = btoa('Hello World');
console.log(encoded); // "SGVsbG8gV29ybGQ="
// 編碼 JSON
const json = JSON.stringify({ name: 'John', age: 30 });
const encodedJson = btoa(json);
console.log(encodedJson); // "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9"- > 僅接受 ASCII 字元 (0-255)
- > 對 Unicode 字元會拋出錯誤
- > 在所有現代瀏覽器和 Node.js 16+ 中可用
atob() - 從 Base64 解碼
`atob()` 函數解碼 Base64 編碼的字串。
// 基本用法
const decoded = atob('SGVsbG8gV29ybGQ=');
console.log(decoded); // "Hello World"
// 解碼 JSON
const decodedJson = atob('eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9');
const data = JSON.parse(decodedJson);
console.log(data); // { name: 'John', age: 30 }- > 回傳二進位字串
- > 對無效的 Base64 會拋出錯誤
- > 區分大小寫的輸入
Unicode 處理
對於 Unicode 字串,結合 TextEncoder/TextDecoder 使用。
// 編碼 Unicode
function encodeUnicode(str) {
  const bytes = new TextEncoder().encode(str);
  const binString = String.fromCharCode(...bytes);
  return btoa(binString);
}
// 解碼 Unicode
function decodeUnicode(base64) {
  const binString = atob(base64);
  const bytes = Uint8Array.from(binString, c => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}
// 範例
const encoded = encodeUnicode('你好世界 🌍');
const decoded = decodeUnicode(encoded);
console.log(decoded); // "你好世界 🌍"常見使用案例
網路開發中的實際應用。
錯誤處理
穩健程式碼的最佳實踐。
function safeBase64Decode(str) {
  try {
    return atob(str);
  } catch (e) {
    console.error('無效的 Base64:', e);
    return null;
  }
}
function safeBase64Encode(str) {
  try {
    return btoa(str);
  } catch (e) {
    // 可能是 Unicode 問題
    return btoa(unescape(encodeURIComponent(str)));
  }
}瀏覽器和 Node.js 支援
跨環境可用性。
// 舊版 Node.js 的後備方案
if (typeof btoa === 'undefined') {
  global.btoa = (str) => Buffer.from(str, 'binary').toString('base64');
  global.atob = (b64) => Buffer.from(b64, 'base64').toString('binary');
}效能提示
優化 Base64 操作。
// 效能比較
const cache = new Map();
function cachedBtoa(str) {
  if (!cache.has(str)) {
    cache.set(str, btoa(str));
  }
  return cache.get(str);
}- > 為重複使用快取編碼值
- > 對大檔案使用串流
- > 考慮二進位資料的替代方案 (ArrayBuffer, Blob)
- > 盡可能批次處理操作