What is the buffer in Node.js?
Why Interviewers Ask This
This is a classic screening question for Node.js roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
A Buffer in Node.js is a fixed-size chunk of memory (allocated outside the V8 heap) for handling raw binary data — bytes. Buffers are essential for working with streams, file I/O, network protocols, and binary data (images, audio, encrypted data) where JavaScript's native string handling is insufficient. Creating buffers: Buffer.alloc(size) — creates a zero-initialized buffer of the specified size (safe); Buffer.from(string, encoding) — creates a buffer from a string; Buffer.from(array) — from an array of bytes. Key methods: buf.toString(encoding) — convert to string; buf.length — byte length; buf.slice(start, end) — create a view; Buffer.concat([buf1, buf2]) — concatenate buffers. Supported encodings include utf8, base64, hex, binary, ascii. Node.js 10+ recommends Buffer.alloc() over the deprecated new Buffer() constructor.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Node.js answers easy to follow.
Previous
What is the difference between synchronous and asynchronous code in Node.js?
Next
What are streams in Node.js?