Reference

JavaScript中的Base64

JavaScript中Base64编解码完整指南:浏览器中使用btoa/atob,Node.js中使用Buffer。

浏览器中的Base64

// 编码
const encoded = btoa('Hello World');
// "SGVsbG8gV29ybGQ="

// 解码
const decoded = atob('SGVsbG8gV29ybGQ=');
// "Hello World"

Node.js中的Base64

const encoded = Buffer.from('Hello World').toString('base64');
const decoded = Buffer.from('SGVsbG8gV29ybGQ=', 'base64').toString('utf8');

常见问题

为什么btoa()对特殊字符失败?

btoa()只接受Latin-1字符。对于Unicode,请使用TextEncoder或encodeURIComponent。