Intermediate Node.js Interview QuestionsIntermediateConcept
Node.js · Question 54
What is a Buffer in Node.js?
Direct answer
Buffer is Node's fixed-length raw binary data type — like Uint8Array for bytes from files, sockets, and crypto; use Buffer.from/alloc, avoid deprecated constructors, and specify encoding (utf8, hex, base64) when converting to strings.
JavaScript strings are UTF-16; Buffers hold bytes for I/O that is not text — images, hashes, TLS, file chunks in streams. Before TypedArrays were universal, Buffer was the Node binary workhorse.
Why interviewers ask
| API | Purpose |
|---|---|
| Buffer.from(str, 'utf8') | String → bytes |
| buf.toString('hex') | Bytes → hex display |
| Buffer.alloc(n) | Zero-filled n-byte buffer |
| Buffer.concat(arr) | Join buffer chunks from stream |
| buf.length | Byte size, not character count |
- Stream chunks — default 'data' events emit Buffer unless encoding set on readable.
- Uint8Array interop — modern APIs accept both; Buffer is Uint8Array subclass.
- Security — zero fill on alloc; wipe sensitive buffers when done if handling secrets.
buffer-basics.mjs
const text = "AceDevHub";
const buf = Buffer.from(text, "utf8");
console.log(buf.length); // bytes
console.log(buf.toString("hex"));
const chunks = [Buffer.from("hel"), Buffer.from("lo")];
const joined = Buffer.concat(chunks).toString("utf8"); // "hello"