JavaScript atob() と btoa() 関数
JavaScript組み込みのBase64エンコード・デコード関数のクイックリファレンス。
|
btoa() - Base64へエンコード
`btoa()`関数はバイナリデータからBase64エンコードされたASCII文字列を作成します。
// 基本的な使い方
const encoded = btoa('Hello World');
console.log(encoded); // "SGVsbG8gV29ybGQ="
// JSONのエンコード
const json = JSON.stringify({ name: 'John', age: 30 });
const encodedJson = btoa(json);
console.log(encodedJson); // "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9"
- > ASCII文字(0-255)のみ受け付ける
- > Unicode文字はエラーを投げる
- > 全ての現代ブラウザとNode.js 16+で利用可能
atob() - Base64からデコード
`atob()`関数はBase64エンコードされた文字列をデコードします。
// 基本的な使い方
const decoded = atob('SGVsbG8gV29ybGQ=');
console.log(decoded); // "Hello World"
// JSONのデコード
const decodedJson = atob('eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9');
const data = JSON.parse(decodedJson);
console.log(data); // { name: 'John', age: 30 }
- > バイナリ文字列を返す
- > 無効なBase64はエラーを投げる
- > 入力は大文字小文字を区別
Unicodeの処理
Unicode文字列の場合、TextEncoder/TextDecoderと組み合わせます。
// Unicodeエンコード
function encodeUnicode(str) {
const bytes = new TextEncoder().encode(str);
const binString = String.fromCharCode(...bytes);
return btoa(binString);
}
// Unicodeデコード
function decodeUnicode(base64) {
const binString = atob(base64);
const bytes = Uint8Array.from(binString, c => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
// 例
const encoded = encodeUnicode('こんにちは世界 🌍');
const decoded = decodeUnicode(encoded);
console.log(decoded); // "こんにちは世界 🌍"
一般的な使用例
Web開発での実践的な応用。
エラー処理
堅牢なコードのベストプラクティス。
function safeBase64Decode(str) {
try {
return atob(str);
} catch (e) {
console.error('無効なBase64:', e);
return null;
}
}
function safeBase64Encode(str) {
try {
return btoa(str);
} catch (e) {
// おそらくUnicodeの問題
return btoa(unescape(encodeURIComponent(str)));
}
}
ブラウザとNode.jsサポート
環境間での利用可能性。
// Node.js古いバージョン用のフォールバック
if (typeof btoa === 'undefined') {
global.btoa = (str) => Buffer.from(str, 'binary').toString('base64');
global.atob = (b64) => Buffer.from(b64, 'base64').toString('binary');
}
パフォーマンスのヒント
Base64操作の最適化。
// パフォーマンス比較
const cache = new Map();
function cachedBtoa(str) {
if (!cache.has(str)) {
cache.set(str, btoa(str));
}
return cache.get(str);
}
- > 繰り返し使用する値はキャッシュする
- > 大きなファイルにはストリーミングを使用
- > バイナリデータの代替案を検討(ArrayBuffer、Blob)
- > 可能な限りバッチ処理