🔐
← ガむド䞀芧に戻る

JavaScript での Base64 ゚ンコヌド/デコヌド: btoa()、atob()、Unicode

· タグ: javascript, base64, btoa, atob, nodejs, encoding, web-development

JavaScript での Base64 ゚ンコヌディングずデコヌディング

JavaScript には、Base64 文字列を゚ンコヌドおよびデコヌドするための組み蟌みの方法がいく぀かありたす。ブラりザアプリケヌションを構築しおいる堎合でも、Node.js サヌバヌを構築しおいる堎合でも、JSON、HTML、URL などのテキストベヌスの圢匏でバむナリデヌタを扱うには、Base64 の操䜜方法を理解するこずが䞍可欠です。

ブラりザでの btoa() ず atob() の䜿甚

ブラりザの JavaScript で Base64 を扱うための 2 ぀の䞭心的な関数は、btoa() ず atob() です。これらの関数名は叀い呜名芏則に埓っおいたす — btoa は「binary to ASCII」の略で、atob は「ASCII to binary」の略です。これらは䜕十幎もの間、すべおの䞻芁ブラりザでサポヌトされおきたした。

btoa() での゚ンコヌディング

const originalString = 'Hello, world!';
const encoded = btoa(originalString);
console.log(encoded);
// Output: SGVsbG8sIHdvcmxkIQ==

atob() でのデコヌディング

const base64String = 'SGVsbG8sIHdvcmxkIQ==';
const decoded = atob(base64String);
console.log(decoded);
// Output: Hello, world!

どちらの関数も、Latin-1 文字各文字が 1 バむトで衚されるのみを含む文字列で動䜜したす。これは重芁な制限であり、次に説明したす。

Unicode 文字ず非 ASCII 文字の凊理

よくある萜ずし穎: btoa() は、絵文字、䞭囜語文字、アクセント付き文字など、Latin-1 の範囲倖の文字を含む文字列が枡されるず゚ラヌをスロヌしたす。

btoa('Hello 䜠奜');
// Error: The string to be encoded contains characters outside of the Latin-1 range.

Unicode 文字列を゚ンコヌドするには、たず文字列をバむトに倉換しおから、そのバむトを゚ンコヌドする必芁がありたす。最新のアプロヌチでは、TextEncoder ず TextDecoder API を䜿甚したす:

function unicodeToBase64(str) {
  const bytes = new TextEncoder().encode(str);
  const binaryString = String.fromCharCode(...bytes);
  return btoa(binaryString);
}

function base64ToUnicode(base64) {
  const binaryString = atob(base64);
  const bytes = Uint8Array.from(binaryString, (c) => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

// Usage
const encoded = unicodeToBase64('Hello 䜠奜 🚀');
console.log(encoded);
// Output: SGVsbG8g5L2g5aW9IPCfj4A=

const decoded = base64ToUnicode(encoded);
console.log(decoded);
// Output: Hello 䜠奜 🚀

叀い手法では encodeURIComponent ず decodeURIComponent を䜿甚したすが、TextEncoder/TextDecoder のアプロヌチの方が堅牢で、掚奚される最新の゜リュヌションです。

バむナリデヌタの゚ンコヌディングArrayBuffer

fetch や FileReader などの API からファむル、画像、生のバむナリデヌタを扱う堎合、通垞は ArrayBuffer たたは Uint8Array を取埗したす。これを Base64 に倉換する方法は次のずおりです:

function arrayBufferToBase64(buffer) {
  const bytes = new Uint8Array(buffer);
  let binaryString = '';
  for (let i = 0; i < bytes.length; i++) {
    binaryString += String.fromCharCode(bytes[i]);
  }
  return btoa(binaryString);
}

function base64ToArrayBuffer(base64) {
  const binaryString = atob(base64);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes.buffer;
}

ブラりザでファむルを Base64 に倉換する

FileReader を䜿甚しお、ナヌザヌが遞択したファむルを Base64 デヌタ URL に倉換する完党な䟋を次に瀺したす:

function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = () => reject(new Error('Failed to read file'));
    reader.readAsDataURL(file);
  });
}

// Usage with a file input
document.querySelector('input[type="file"]').addEventListener('change', async (e) => {
  const file = e.target.files[0];
  try {
    const dataUrl = await fileToBase64(file);
    console.log(dataUrl); // data:image/png;base64,iVBORw0KGgo...
  } catch (err) {
    console.error('Conversion failed:', err);
  }
});

Node.js での Base64 の䜿甚

Node.js は Base64 操䜜甚の Buffer クラスを提䟛しおおり、ブラりザの btoa/atob よりも柔軟です。Buffer クラスは Unicode を含む゚ンコヌドずデコヌドを自動的に凊理し、耇数の゚ンコヌド圢匏をサポヌトしたす。

基本的な゚ンコヌディングずデコヌディング

// Encode a string to Base64
const encoded = Buffer.from('Hello, world!').toString('base64');
console.log(encoded);
// Output: SGVsbG8sIHdvcmxkIQ==

// Decode a Base64 string back to text
const decoded = Buffer.from(encoded, 'base64').toString('utf-8');
console.log(decoded);
// Output: Hello, world!

Node.js での Unicode サポヌト

ブラりザの btoa() ずは異なり、Node.js の Buffer は Unicode をシヌムレスに凊理したす:

const encoded = Buffer.from('Hello 䜠奜 🚀').toString('base64');
console.log(encoded);
// Output: SGVsbG8g5L2g5aW9IPCfj4A=

const decoded = Buffer.from(encoded, 'base64').toString('utf-8');
console.log(decoded);
// Output: Hello 䜠奜 🚀

ファむルの読み取りず Base64 ぞの゚ンコヌディング

const fs = require('fs');

// Read a file and encode it to Base64
const buffer = fs.readFileSync('image.png');
const base64 = buffer.toString('base64');
const dataUrl = `data:image/png;base64,${base64}`;

Node.js での Base64url ゚ンコヌディング

Node.js 15.7.0 以降ではネむティブの Base64url ゚ンコヌディングをサポヌトしおおり、+ を - に、/ を _ に眮き換えおパディングを省略したす:

const encoded = Buffer.from('Hello, world!').toString('base64url');
console.log(encoded);
// Output: SGVsbG8sIHdvcmxkIQ (no padding)

const decoded = Buffer.from(encoded, 'base64url').toString('utf-8');
console.log(decoded);
// Output: Hello, world!

パフォヌマンスに関する考慮事項

倧芏暡なデヌタの堎合、Base64 操䜜を繰り返すず遅くなる可胜性がありたす。いく぀かのヒントを玹介したす:

  • Unicode 文字列では手動倉換ではなく TextEncoder/TextDecoder を䜿甚する
  • Node.js では、Buffer.from() は高床に最適化されおいたす — 手動実装よりも優先しおください
  • 必芁な堎合を陀き、倧きなファむルを Base64 に倉換しないようにするストリヌミングを怜蚎する
  • 倧芏暡なデヌタセットでは、メむンスレッドのブロッキングを避けるために、ブラりザで Blob ず FileReader の䜿甚を怜蚎する

Base64 ゚ンコヌディングをオンラむンで詊す

無料のオンラむン Base64 ゚ンコヌダずデコヌダを䜿っお、ブラりザで盎接゚ンコヌドずデコヌドを詊しおみたしょう。コヌディングは䞍芁です — テキストを貌り付けるかファむルをアップロヌドするだけで、Base64 の結果が即座に埗られたす。

JavaScript での Base64 ゚ンコヌド/デコヌド: btoa()、atob()、Unicode - CoolTool