What is a buffer in Node.js?
Buffers in Node.js
A Buffer is a fixed-size chunk of memory allocated outside the V8 heap, used to work with binary data directly. Buffers are essential when dealing with streams, file I/O, network protocols, and encoding conversions.
Why Buffers?
JavaScript strings are UTF-16, which is great for text but wasteful for binary data (images, files, TCP packets). Buffers represent raw binary data as a sequence of bytes.
Creating Buffers
// From string
const buf1 = Buffer.from('Hello, Node.js!', 'utf8');
// From array of bytes
const buf2 = Buffer.from([72, 101, 108, 108, 111]);
// Allocate safe (zeroed) buffer
const buf3 = Buffer.alloc(10); // 10 bytes, all zeros
// Allocate uninitialized (faster, but may contain old data)
const buf4 = Buffer.allocUnsafe(10); // use with caution!
// From hex string
const buf5 = Buffer.from('48656c6c6f', 'hex');Reading & Writing
const buf = Buffer.alloc(4);
// Write bytes
buf.writeUInt8(0x48, 0); // 'H'
buf.writeUInt8(0x69, 1); // 'i'
// Read bytes
console.log(buf[0]); // 72
console.log(buf.toString('utf8')); // 'Hi'
// Inspect
console.log(buf.length); // 4
console.log(buf); // <Buffer 48 69 00 00>Encoding Support
const buf = Buffer.from('Hello');
buf.toString('utf8'); // 'Hello'
buf.toString('hex'); // '48656c6c6f'
buf.toString('base64'); // 'SGVsbG8='
buf.toString('ascii'); // 'Hello'Slicing & Copying
const buf = Buffer.from('Hello, World!');
// slice references the same memory
const slice = buf.slice(0, 5);
console.log(slice.toString()); // 'Hello'
// copy creates a new buffer
const copy = Buffer.alloc(5);
buf.copy(copy, 0, 0, 5);
console.log(copy.toString()); // 'Hello'
// Modern: subarray (same as slice)
const sub = buf.subarray(7, 12);
console.log(sub.toString()); // 'World'Buffers in Streams
const fs = require('fs');
fs.createReadStream('./image.png').on('data', (chunk) => {
// chunk is a Buffer
console.log(`Received ${chunk.length} bytes`);
});Buffer vs TypedArray
Since Node.js 4, Buffer is a subclass of Uint8Array. You can use TypedArray methods on Buffer:
const buf = Buffer.from([1, 2, 3, 4, 5]);
const arr = new Uint8Array(buf);
// They share the same memorySummary
Buffer = raw binary memory outside V8. Use it when handling binary protocols, file I/O, encryption, compression, or any data that isn't plain text. Always specify encoding when converting between Buffer and string.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.