Base64 en el Navegador
// Codificar
const encoded = btoa('Hello World');
// Resultado: "SGVsbG8gV29ybGQ="
// Decodificar
const decoded = atob('SGVsbG8gV29ybGQ=');
// Resultado: "Hello World"Manejo de Unicode con btoa()
// Codificar texto Unicode
function b64EncodeUnicode(str) {
return btoa(new TextEncoder().encode(str).reduce(
(data, byte) => data + String.fromCharCode(byte), ''
));
}Base64 en Node.js
// Codificar
const encoded = Buffer.from('Hello World').toString('base64');
// Decodificar
const decoded = Buffer.from('SGVsbG8gV29ybGQ=', 'base64').toString('utf8');Preguntas Frecuentes
¿Por qué btoa() falla con caracteres especiales?
btoa() solo admite Latin-1 (bytes 0-255). Para Unicode usa TextEncoder o el patrón encodeURIComponent.
¿Base64 URL-safe en JavaScript?
btoa(str).replace(/+/g,'-').replace(///g,'_').replace(/=/g,'')