Backend & Node.js · APIs, data and failure
What are Buffers and when do you use them?
Short answer
A Buffer is a fixed-length view over raw bytes, used for binary data such as files, network packets and image encoding. It is a subclass of Uint8Array with Node-specific helpers.
JavaScript strings are for text, not arbitrary bytes. Buffers let Node represent binary data without encoding it. Most stream chunks are buffers, and APIs that work with files, sockets, crypto and compression accept or return them.
const fromString = Buffer.from("hello", "utf8");
const safe = Buffer.alloc(8);
const fast = Buffer.allocUnsafe(8);
const slice = fromString.subarray(0, 2);
console.log(fromString.length);
console.log(safe.toString("hex"));
console.log(slice.toString("utf8"));
console.log(slice.buffer === fromString.buffer);What to watch
- Buffer.alloc zeroes memory; Buffer.allocUnsafe may expose old data, so always fill it
- subarray and slice share memory, while Buffer.from with a copy creates new storage
- Sizes are in bytes, not characters, so multibyte text has a larger length
- Set an encoding when converting to a string, and handle malformed input explicitly
- Buffers are not resizable; allocate the right size or collect chunks into a list
The usual mistake is concatenating buffers in a loop with repeated Buffer.concat calls, which copies the accumulated data every time. Collect chunks in an array and concatenate once, or stream the data instead of holding it.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between Buffer.alloc and Buffer.allocUnsafe?
- 2Do Buffer slices copy data?
- 3How do you safely concatenate many chunks?
- 4Why does buffer length differ from string length for emoji?
Say it in the interview
A Buffer is a fixed-size byte array used for binary data like files, sockets and crypto output. Buffer.from converts strings or arrays, Buffer.alloc gives me zeroed memory, and allocUnsafe is faster but may contain stale bytes. Slices share memory, so I copy when the source will be reused. For many chunks I collect them and concatenate once rather than repeatedly copying.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Backend & Node.js mock interview and get scored feedback on depth, clarity and confidence.