SHIN
Node.js 실전 팁 20선
20편Buffer는 Node.js에서 바이너리 데이터를 다루는 핵심 클래스입니다. 파일, 네트워크, 암호화 작업에서 필수적으로 등장합니다.
// 1. 크기로 생성 (초기화됨)
const buf1 = Buffer.alloc(10); // 10바이트, 0으로 채움
// 2. 배열로 생성
const buf2 = Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f]); // 'Hello'
// 3. 문자열로 생성
const buf3 = Buffer.from('Hello, World!', 'utf-8');
// ❌ Buffer() 생성자는 deprecated
// new Buffer(10) → 사용 금지const text = 'Hello 안녕';
const buf = Buffer.from(text, 'utf-8');
// Buffer → 문자열
buf.toString('utf-8') // 'Hello 안녕'
buf.toString('hex') // '48656c6c6f20ec9588eb8595'
buf.toString('base64') // 'SGVsbG8g7JWI64eA'
buf.toString('base64url') // URL-safe base64
// 문자열 → Buffer
Buffer.from('SGVsbG8=', 'base64').toString('utf-8') // 'Hello'import { readFile, writeFile } from 'fs/promises';
// 이미지 파일 → base64
async function imageToBase64(imagePath) {
const buf = await readFile(imagePath);
return buf.toString('base64');
}
// base64 → 이미지 파일
async function base64ToImage(base64, outputPath) {
const buf = Buffer.from(base64, 'base64');
await writeFile(outputPath, buf);
}const a = Buffer.from('Hello');
const b = Buffer.from('World');
// 결합
const combined = Buffer.concat([a, Buffer.from(' '), b]);
console.log(combined.toString()); // 'Hello World'
// 비교 (0: 같음, -1: a<b, 1: a>b)
Buffer.compare(a, b); // 음수 (H < W)
// 같은지 확인 (타이밍 공격 방지에는 crypto.timingSafeEqual 사용)
a.equals(Buffer.from('Hello')); // true// Buffer → Uint8Array
const buf = Buffer.from([1, 2, 3]);
const uint8 = new Uint8Array(buf);
// Uint8Array → Buffer (복사 없이)
const buf2 = Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength);
// ArrayBuffer → Buffer
const ab = new ArrayBuffer(4);
const view = new DataView(ab);
view.setInt32(0, 0xDEADBEEF);
const buf3 = Buffer.from(ab);
console.log(buf3.toString('hex')); // 'deadbeef'const chunks = [];
stream.on('data', (chunk) => chunks.push(chunk));
stream.on('end', () => {
const full = Buffer.concat(chunks);
const text = full.toString('utf-8');
console.log(text);
});성능 팁:
Buffer.allocUnsafe()는 초기화 없이 빠르게 할당하지만, 이전 메모리 내용이 남아있을 수 있어 외부에 노출되는 데이터에는 절대 사용하지 마세요.