[CODE] Base64 in JavaScript
Practical JavaScript examples for Base64 encoding and decoding with modern browser APIs.
// BASIC ENCODING & DECODING
JavaScript provides built-in functions for Base64 operations. The btoa() and atob() functions handle basic encoding and decoding:
These functions work great for ASCII text, but require special handling for Unicode characters.
// Basic Base64 encoding
const text = 'Hello World';
const encoded = btoa(text);
console.log(encoded); // SGVsbG8gV29ybGQ=
// Basic Base64 decoding
const decoded = atob(encoded);
console.log(decoded); // Hello World
// Check if string is valid Base64
function isValidBase64(str) {
try {
return btoa(atob(str)) === str;
} catch (err) {
return false;
}
}
// UNICODE SUPPORT
For Unicode strings, we need to convert to UTF-8 bytes first. Modern browsers provide TextEncoder and TextDecoder APIs:
This approach correctly handles emoji, international characters, and other Unicode content.
// Unicode-safe Base64 encoding
function encodeBase64(str) {
const encoder = new TextEncoder();
const bytes = encoder.encode(str);
const binary = String.fromCharCode(...bytes);
return btoa(binary);
}
// Unicode-safe Base64 decoding
function decodeBase64(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
const decoder = new TextDecoder();
return decoder.decode(bytes);
}
// Example with emoji
const emoji = 'Hello 👋 World 🌍';
const encoded = encodeBase64(emoji);
const decoded = decodeBase64(encoded);
console.log(decoded); // Hello 👋 World 🌍
// FILE HANDLING
Converting files to Base64 is common for uploads and data URIs. Use FileReader API for client-side file processing:
This creates data URIs that can be embedded directly in HTML or sent to APIs.
// Convert file to Base64 data URI
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
reader.readAsDataURL(file);
});
}
// Usage with file input
document.getElementById('fileInput').addEventListener('change', async (e) => {
const file = e.target.files[0];
if (file) {
try {
const base64 = await fileToBase64(file);
console.log(base64);
// Result: data:image/png;base64,iVBORw0KGgoAAAA...
} catch (error) {
console.error('Error:', error);
}
}
});
// URL-SAFE BASE64
Standard Base64 uses + and / characters that need URL encoding. URL-safe Base64 replaces these with - and _:
This is essential for tokens, IDs, and other data transmitted via URLs.
// Convert to URL-safe Base64
function toUrlSafeBase64(base64) {
return base64
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
// Convert from URL-safe Base64
function fromUrlSafeBase64(urlSafeBase64) {
let base64 = urlSafeBase64
.replace(/-/g, '+')
.replace(/_/g, '/');
// Add padding if needed
const padding = 4 - (base64.length % 4);
if (padding !== 4) {
base64 += '='.repeat(padding);
}
return base64;
}
// Example
const text = 'URL-safe encoding test';
const encoded = btoa(text);
const urlSafe = toUrlSafeBase64(encoded);
console.log(urlSafe); // VVJMLXNhZmUgZW5jb2RpbmcgdGVzdA
// STREAMING LARGE DATA
For large files or data streams, process in chunks to avoid memory issues:
This approach prevents browser freezing and handles large datasets efficiently.
// Stream-based Base64 encoding
class Base64Encoder {
constructor() {
this.buffer = '';
}
encode(chunk) {
this.buffer += chunk;
const completeBytes = Math.floor(this.buffer.length / 3) * 3;
const toEncode = this.buffer.slice(0, completeBytes);
this.buffer = this.buffer.slice(completeBytes);
return btoa(toEncode);
}
flush() {
if (this.buffer.length > 0) {
const result = btoa(this.buffer);
this.buffer = '';
return result;
}
return '';
}
}
// Usage
const encoder = new Base64Encoder();
let result = '';
result += encoder.encode('First chunk');
result += encoder.encode(' Second chunk');
result += encoder.flush();
console.log(result);
// ERROR HANDLING
Always implement proper error handling for Base64 operations:
Robust error handling prevents application crashes and provides better user experience.
// Safe Base64 operations with error handling
function safeEncode(input) {
try {
if (typeof input !== 'string') {
throw new Error('Input must be a string');
}
return btoa(input);
} catch (error) {
console.error('Encoding error:', error.message);
return null;
}
}
function safeDecode(base64) {
try {
// Validate Base64 format
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64)) {
throw new Error('Invalid Base64 format');
}
return atob(base64);
} catch (error) {
console.error('Decoding error:', error.message);
return null;
}
}
// Usage
const encoded = safeEncode('Hello World');
const decoded = safeDecode(encoded);
if (encoded && decoded) {
console.log('Success:', decoded);
}