모든 게시글개발

JavaScript에서 Base64 완벽 가이드

btoa, atob 함수의 사용법과 한글 처리, 파일 변환 등 실전 예제를 다룹니다.

23분 읽기

JavaScript의 Base64 함수

JavaScript는 브라우저와 Node.js 환경 모두에서 Base64 인코딩/디코딩을 지원합니다.

btoa()와 atob()

기본 사용법

// 인코딩 (Binary to ASCII) const encoded = btoa('Hello'); console.log(encoded); // "SGVsbG8=" // 디코딩 (ASCII to Binary) const decoded = atob(encoded); console.log(decoded); // "Hello"

함수 이름의 의미

  • btoa: Binary to ASCII - 바이너리를 ASCII로 변환 (인코딩)
  • atob: ASCII to Binary - ASCII를 바이너리로 변환 (디코딩)

한글 처리하기

btoa()는 Latin1 문자(0-255)만 지원하므로 한글을 직접 처리할 수 없습니다. 다음과 같은 방법으로 해결할 수 있습니다:

방법 1: encodeURIComponent 사용

// 한글 인코딩 function encodeUnicode(str) { return btoa(unescape(encodeURIComponent(str))); } // 한글 디코딩 function decodeUnicode(str) { return decodeURIComponent(escape(atob(str))); } const korean = '안녕하세요'; const encoded = encodeUnicode(korean); console.log(encoded); // "7JWI64WV7ZWY7IS47JqU" const decoded = decodeUnicode(encoded); console.log(decoded); // "안녕하세요"

방법 2: TextEncoder/TextDecoder 사용 (모던 방식)

// 인코딩 function encode(str) { const bytes = new TextEncoder().encode(str); const binString = Array.from(bytes, (byte) => String.fromCodePoint(byte), ).join(""); return btoa(binString); } // 디코딩 function decode(str) { const binString = atob(str); const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0)); return new TextDecoder().decode(bytes); } console.log(encode('안녕하세요')); console.log(decode(encode('안녕하세요')));

파일을 Base64로 변환

이미지 파일 변환

function fileToBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); }); } // 사용 예 const input = document.querySelector('input[type="file"]'); input.addEventListener('change', async (e) => { const file = e.target.files[0]; const base64 = await fileToBase64(file); console.log(base64); // data:image/png;base64,iVBORw0KG... });

Base64를 파일로 변환

function base64ToFile(base64, filename) { // Data URI에서 Base64 부분만 추출 const arr = base64.split(','); const mime = arr[0].match(/:(.*?);/)[1]; const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, { type: mime }); } // 사용 예 const file = base64ToFile(base64String, 'image.png');

Web Worker로 대용량 파일 처리

대용량 파일을 처리할 때는 Web Worker를 사용하여 메인 스레드 블로킹을 방지하세요.

Worker 파일 (base64-worker.js)

// base64-worker.js self.onmessage = async (e) => { const { file } = e.data; const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { self.postMessage({ result: reader.result }); }; reader.onerror = () => { self.postMessage({ error: 'Failed to read file' }); }; };

메인 스레드에서 사용

const worker = new Worker('base64-worker.js'); worker.onmessage = (e) => { const { result, error } = e.data; if (error) { console.error(error); } else { console.log('Base64 result:', result); } }; // 파일 전송 worker.postMessage({ file: selectedFile });

Base64 유효성 검사

function isValidBase64(str) { try { return btoa(atob(str)) === str; } catch (err) { return false; } } console.log(isValidBase64('SGVsbG8=')); // true console.log(isValidBase64('invalid!')); // false

성능 최적화 팁

1. 청크 단위로 처리

대용량 데이터는 청크로 나누어 처리하면 메모리 사용량을 줄일 수 있습니다.

async function processInChunks(file, chunkSize = 1024 * 1024) { const chunks = []; let offset = 0; while (offset < file.size) { const chunk = file.slice(offset, offset + chunkSize); const base64 = await fileToBase64(chunk); chunks.push(base64.split(',')[1]); // Base64 부분만 offset += chunkSize; } return chunks.join(''); }

2. 캐싱 활용

동일한 데이터를 반복 변환하는 경우 캐싱을 활용하세요:

const cache = new Map(); function cachedEncode(str) { if (cache.has(str)) { return cache.get(str); } const encoded = btoa(str); cache.set(str, encoded); return encoded; }

Node.js에서 사용하기

Node.js에서는 Buffer를 사용합니다:

// 인코딩 const encoded = Buffer.from('안녕하세요').toString('base64'); console.log(encoded); // 디코딩 const decoded = Buffer.from(encoded, 'base64').toString('utf-8'); console.log(decoded);

마치며

JavaScript의 Base64 처리는 웹 개발에서 매우 자주 사용됩니다. 한글 처리와 대용량 파일 처리에 주의하면서 적절히 활용하세요.

더 편리한 변환을 원하신다면 Base64 변환기를 사용해보세요!

관련 게시글