What is a Buffer, and when do you use one?
Quick Answer
A Buffer is a fixed-length chunk of raw binary memory outside V8's heap, used to handle binary data — file contents, network packets, crypto, image bytes. It's a subclass of Uint8Array with encoding helpers (utf8, hex, base64) to convert to/from strings.
Detailed Answer
Answer: A Buffer represents a fixed-length sequence of raw bytes. Because JavaScript strings are UTF-16 and not suited to arbitrary binary data, Node uses Buffers for anything binary: file I/O, TCP packets, cryptography, image/video bytes, protocol parsing.
Creating Buffers:
Buffer.from('hello', 'utf8'); // from a string
Buffer.from([0x68, 0x69]); // from bytes
Buffer.alloc(10); // 10 zero-filled bytes (safe)
Buffer.allocUnsafe(10); // faster, but may contain old memory — overwrite before use
Encoding conversions:
const buf = Buffer.from('hello');
buf.toString('utf8'); // 'hello'
buf.toString('hex'); // '68656c6c6f'
buf.toString('base64'); // 'aGVsbG8='
Key facts:
- A Buffer is a subclass of
Uint8Array, so TypedArray methods work on it. - It's allocated outside the V8 heap (in C++), so large Buffers don't pressure V8's garbage collector the same way.
- Fixed size — you can't grow a Buffer; you allocate a new one or use a stream.
Security note: prefer Buffer.alloc over Buffer.allocUnsafe. allocUnsafe skips zero-filling for speed and can expose leftover memory contents if you read before fully writing it.
When you use Buffers directly: implementing binary protocols, hashing/encrypting bytes, manipulating image data, or reading a file's raw bytes. For text you usually just specify an encoding and work with strings.