Buffer là class built-in xử lý binary data — vùng nhớ raw bytes nằm ngoài V8 heap.
- JavaScript thuần không có kiểu dữ liệu binary, Buffer lấp đầy khoảng trống này cho Node.js.
- Cần dùng khi: đọc file binary (ảnh, PDF, executable), xử lý network packets TCP/UDP, mã hóa/giải mã base64 (
Buffer.from('hello').toString('base64')), tính hash vớicrypto.createHash.
Ví dụ thực tế: upload ảnh qua API, req.body là Buffer chứa raw bytes của file, cần convert hoặc pipe trực tiếp lên S3.
Buffer is a built-in class for handling binary data — a region of raw bytes that lives outside the V8 heap.
- Plain JavaScript has no binary data type; Buffer fills that gap in Node.js.
- When you need it: reading binary files (images, PDFs, executables), processing TCP/UDP network packets, base64 encoding/decoding (
Buffer.from('hello').toString('base64')), computing hashes withcrypto.createHash. - Practical example: uploading an image via API,
req.bodyis a Buffer containing the raw bytes of the file — either convert it or pipe it directly to S3.
Pitfall: Buffer.allocUnsafe(size) is faster but contains leftover memory data — only use it when you'll immediately overwrite the entire buffer; use Buffer.alloc(size) (zero-filled) in all other cases.