What is a Buffer in Node.js and why does it exist?
A Buffer is a fixed-size chunk of raw memory holding bytes. Node uses it for binary data such as files, network packets and images, because JavaScript strings are meant for text, not raw bytes.
Explain it simply
A file on disk or a packet on the network is just a long run of numbers from 0 to 255, called bytes. A Buffer is a box that holds those numbers exactly as they are. It is like a tray of numbered sweets: each slot holds one value, and the tray size is fixed once you make it.
Text only makes sense once you decide how to turn bytes into letters, which is what an encoding such as UTF-8 does.
Example
const buf = Buffer.from("Hi", "utf8");
console.log(buf); // <Buffer 48 69>
console.log(buf.length); // 2
console.log(buf[0]); // 72 (the byte for "H")
console.log(buf.toString()); // Hi
const empty = Buffer.alloc(4); // four zero bytes, safe to use
console.log(empty); // <Buffer 00 00 00 00>Key points:
- A Buffer is a subclass of
Uint8Array, so array-style access works. Buffer.alloc(n)gives zero-filled memory.Buffer.allocUnsafe(n)is faster but may contain old data, so fill it before use.fs.readFilewithout an encoding returns a Buffer.- Length is in bytes, not characters:
Buffer.from("₹").lengthis 3.
What to say in the interview
"A Buffer is fixed-size raw memory for binary data, a Uint8Array subclass. Streams, files and sockets use it. Text conversion needs an explicit encoding, and length counts bytes, not characters."
Common mistakes
- Using
new Buffer(), which is deprecated and unsafe. - Assuming
buf.lengthequals the number of characters.