intermediate
Buffers
Work with binary data, encodings, typed-array behavior, byte length, file/network payloads, and memory ownership.
Buffer is Node's fixed-length binary data type — backed by allocated memory outside the V8 heap (with pooling for small allocations). It bridges file I/O, sockets, crypto, and typed arrays.
const buf = Buffer.from('hello', 'utf8');
console.log(buf.length); // 5 bytes, not string length for non-ASCII
console.log(buf.toString('hex')); // 68656c6c6f
const view = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
Encoding matters: `utf8` is default; `base64` and `hex` are common for transport; never assume one character equals one byte. `Buffer.alloc(n)` zero-fills; `Buffer.allocUnsafe(n)` may contain old memory — faster but must be overwritten before sharing.
On interviews: explain byte length vs string length, when to use Buffer vs Uint8Array, and why mutating a Buffer slice affects the parent unless copied.
Common pitfalls: concatenating buffers in a loop with `+=` on strings; using `allocUnsafe` for secrets; confusing `buffer.length` with character count for Unicode.
The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.
Checklist:
- Know `from`, `alloc`, `concat`, `subarray` vs `slice`.
- Specify encoding on `toString` and `from`.
- Prefer streams for large binary payloads.
- Zero sensitive buffers when feasible.