js中 btoa 方法 和 atob方法介绍
在 JavaScript 中,btoa()
和 atob()
是两个内置的 Base64 编码/解码 方法,用于在字符串与 Base64 编码之间相互转换。
它们的名字来源于:
btoa
= binary to ASCIIatob
= ASCII to binary
🧩 一、btoa()
—— 将字符串编码为 Base64
📘 语法:
btoa(string)
📥 参数:
string
:要进行编码的字符串(只能包含 Latin1 字符,即每个字符的代码点在 0x00 到 0xFF 之间)。
📤 返回值:
- 返回该字符串的 Base64 编码形式。
✅ 示例:
const str = "Hello World!";
const encoded = btoa(str);
console.log(encoded); // 输出: "SGVsbG8gV29ybGQh"
🧩 二、atob()
—— 将 Base64 解码为字符串
📘 语法:
atob(encodedString)
📥 参数:
encodedString
:Base64 格式的字符串。
📤 返回值:
- 解码后的原始字符串。
✅ 示例:
const encoded = "SGVsbG8gV29ybGQh";
const decoded = atob(encoded);
console.log(decoded); // 输出: "Hello World!"
⚠️ 注意事项
1. btoa
/ atob
仅支持 Latin1(单字节字符)
这意味着它们 不能直接处理 UTF-8(例如中文、表情符号等)。
如果直接编码中文,会报错或出现乱码:
btoa("你好"); // ❌ 报错:The string to be encoded contains characters outside of the Latin1 range.
✅ 正确做法:先将字符串转换为 UTF-8 字节,再编码
// 编码中文安全方式
const encoded = btoa(unescape(encodeURIComponent("你好")));
console.log(encoded); // 输出: "5L2g5aW9"// 解码中文安全方式
const decoded = decodeURIComponent(escape(atob(encoded)));
console.log(decoded); // 输出: "你好"
💡 三、现代替代方案(推荐用法)
在现代浏览器或 Node.js 中,推荐使用 TextEncoder
/ TextDecoder
或 Buffer
来处理任意字符的 Base64 编码:
✅ 浏览器(现代 API):
const text = "你好世界";
const encoded = btoa(String.fromCharCode(...new TextEncoder().encode(text)));
console.log(encoded); // 输出: "5L2g5aW977yM5LiW55WM"const decoded = new TextDecoder().decode(Uint8Array.from(atob(encoded), c => c.charCodeAt(0))
);
console.log(decoded); // 输出: "你好世界"
✅ Node.js 环境:
const text = "你好世界";
const encoded = Buffer.from(text, "utf-8").toString("base64");
console.log(encoded); // 输出: "5L2g5aW977yM5LiW55WM"const decoded = Buffer.from(encoded, "base64").toString("utf-8");
console.log(decoded); // 输出: "你好世界"
🧭 总结对比
方法 | 功能 | 仅支持 ASCII | 支持中文 | 适用环境 |
---|---|---|---|---|
btoa() | 字符串 → Base64 | ✅ 是 | ❌ 否 | 浏览器 |
atob() | Base64 → 字符串 | ✅ 是 | ❌ 否 | 浏览器 |
Buffer | 双向转换 | ❌ 否 | ✅ 是 | Node.js |
TextEncoder / TextDecoder | 双向转换 | ❌ 否 | ✅ 是 | 浏览器 & Node.js(现代) |