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); // "안녕하세요 🌍"
일반적인 사용 사례
웹 개발에서의 실용적인 응용.
오류 처리
견고한 코드를 위한 모범 사례.
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)
- > 가능할 때 작업 배치 처리