How to use buffers in Node.js

· Category: Node.js

Short answer

A Buffer is a fixed-size chunk of memory outside the V8 heap used to store raw binary data. Create buffers with Buffer.from(), Buffer.alloc(), or receive them from streams.

How it works

JavaScript strings are UTF-16, which is not efficient for binary data. Buffers store raw bytes and can be converted to strings with a specified encoding like utf8, hex, or base64.

Example

const buf = Buffer.from('Hello');
console.log(buf.toString('hex')); // 48656c6c6f
console.log(buf.toString('base64')); // SGVsbG8=

const empty = Buffer.alloc(10);
empty.write('Node');

Why it matters

Buffers are used by the fs, crypto, net, and http modules to handle binary data efficiently. Without buffers, processing images, files, and network packets would be slow and memory-intensive.