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); // "你好世界 🌍"

常见用例

Web 开发中的实际应用。

错误处理

编写健壮代码的最佳实践。

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)
  • > 尽可能批量操作