Question presented to candidate: "You call buf.subarray(1, 3) and then mutate a byte in the result. Does the original buffer change too, or is the subarray independent — and how would you actually check?"
What a strong answer should cover:
Bufferis Node's class for handling raw binary data — file contents, network packets, cryptographic material, image/video bytes — anything that is not naturally text, plus text that needs precise control over its byte-level encoding.- Buffers are allocated outside the regular JS object heap (covered with real measured numbers in the dedicated memory-leaks question), which is why they can hold large binary payloads without the overhead of ordinary JS object/array memory management.
- 📌 The concrete, verifiable distinction the prompt is really asking about:
Buffer.from(existingBuffer)copies the bytes into new memory — mutating the copy leaves the original untouched..subarray(start, end)returns a view into the same underlying memory — mutating the subarray genuinely mutates the original buffer too, verified directly by watching a string actually change. - Buffers support multiple encodings for converting to/from strings —
utf8,base64,hex, and others — via.toString(encoding)andBuffer.from(str, encoding), letting the same underlying bytes be represented in whichever text form a given API or protocol expects. Buffer.concat([...])joins multiple buffers into one new buffer (a copy, not a view over the inputs) — the standard way to assemble a complete payload from streamed chunks (connecting directly to the dedicated Streams question, where aReadabledelivers data across many separateBufferchunks).Buffer.alloc/Buffer.allocUnsafe/Buffer.from's specific security and performance trade-offs (zero-filling guarantees, uninitialized memory risk) are covered fully, with real measured timing and a real partial-write demonstration, in their own dedicated question.
Clarifying questions expected:
- "Is the concern creating buffers from data, or the copy-vs-view distinction when slicing an existing one?" — the latter is the more commonly misunderstood part.
- "Does this buffer hold sensitive data (like a password hash) where the allocation method's zero-filling guarantee actually matters?" — routes to the dedicated
alloc/allocUnsafe/fromsecurity question.
Code / implementation expected: Yes — actually mutating a .subarray() result and observing the original change (versus Buffer.from(buffer) NOT propagating a mutation) is the concrete, convincing demonstration.