Back to 20 Concepts
internals • Advanced
Buffers, Binary Memory & The 8KB Slab Allocator
Buffers represent raw binary memory allocated outside the V8 JavaScript heap (using C++ malloc). Node.js uses an 8KB Slab Allocator to pre-allocate contiguous chunks for small buffer slices.
Intuitive Mental Model
The Warehouse Pallet: Instead of ordering a delivery truck for every small 100-byte box, the warehouse orders a giant 8KB wooden pallet (Slab) and carves out small parcels as needed.
Node.js ESM / CJS ImplementationNode.js v22 LTS
// Allocates 10 bytes outside V8 heap (zero-filled for security):
const buf = Buffer.alloc(10);
// Buffer from string (UTF-8 binary encoding):
const textBuf = Buffer.from('Hello 🚀', 'utf-8');
console.log(textBuf); // <Buffer 48 65 6c 6c 6f 20 f0 9f 9a 80>
console.log(textBuf.length); // 10 bytes (Rocket emoji takes 4 bytes!)
// Fast uninitialized buffer (Must overwrite before reading!):
const rawBuf = Buffer.allocUnsafe(1024);Key Architectural Takeaways
- •Buffers live in raw C++ memory, bypassing V8 garbage collection overhead for heavy binary I/O.
- •Buffer.allocUnsafe() is faster because it skips zero-filling, but can expose sensitive residual RAM data if read before writing.
- •Buffer.byteLength("🚀") is 4 bytes, whereas "🚀".length in JS string is 2 UTF-16 code units.
Common Production Mistake
Using Buffer.allocUnsafe() and sending it over the network without populating all bytes, leaking memory secrets.
Recommended Solution
Always default to Buffer.alloc() for secure zero-initialized memory.