This page summarizes Base64 usage in JavaScript for both browser and Node.js.
It covers btoa
/atob
, UTF-8 safe helpers, URL-safe variant,
and examples for strings, binary data, and files.
Base64 represents binary data using printable characters.
In browsers, btoa()
encodes a binary string to Base64, and atob()
decodes.
For non-ASCII text, use TextEncoder
/TextDecoder
to handle UTF-8 bytes safely.
In Node.js, use Buffer
.
window.btoa(binaryString)
โ Base64 string (browser)window.atob(base64)
โ binary string (browser)TextEncoder
/ TextDecoder
for UTF-8 bytes (browser)Buffer.from(data).toString('base64')
, Buffer.from(b64, 'base64')
(Node.js)// Encode a JS string (UTF-8) to Base64
function encodeBase64(text) {
const bytes = new TextEncoder().encode(text);
let binary = "";
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
return btoa(binary);
}
// Decode Base64 to JS string (UTF-8)
function decodeBase64(b64) {
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return new TextDecoder('utf-8', { fatal: false }).decode(bytes);
}
console.log(encodeBase64('Hello, ไธ็')); // SGVsbG8sIOS4lueVjw==
console.log(decodeBase64('SGVsbG8sIOS4lueVjw=='));
// String โ Base64
const b64 = Buffer.from('Hello, ไธ็', 'utf8').toString('base64');
console.log(b64); // SGVsbG8sIOS4lueVjw==
// Base64 โ String
const text = Buffer.from('SGVsbG8sIOS4lueVjw==', 'base64').toString('utf8');
console.log(text); // Hello, ไธ็
// Replace +/ with -_, optionally remove padding =
function toUrlSafe(b64, stripPadding = false) {
let s = b64.replace(/\+/g, '-').replace(/\//g, '_');
return stripPadding ? s.replace(/=+$/g, '') : s;
}
function fromUrlSafe(urlSafeB64) {
let s = urlSafeB64.replace(/-/g, '+').replace(/_/g, '/');
// pad to length % 4 === 0
while (s.length % 4) s += '=';
return s;
}
const safe = toUrlSafe('YWJj+/==');
console.log(safe);
console.log(fromUrlSafe(safe));
// File โ Base64 (data URL or raw Base64)
function fileToBase64(file, callback) {
const reader = new FileReader();
reader.onload = () => {
const dataUrl = reader.result; // e.g. "data:image/png;base64,iVBORw0KG..."
const base64 = String(dataUrl).split(',')[1];
callback({ dataUrl, base64 });
};
reader.readAsDataURL(file);
}
// Base64 โ Blob (download)
function base64ToBlob(b64, contentType = 'application/octet-stream') {
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return new Blob([bytes], { type: contentType });
}
TextEncoder/TextDecoder
for UTF-8 safety.=
may be omitted in URL-safe contexts; restore padding before decoding.Buffer
for reliability and performance.