CodePark/ questions / Buffers & binary data
START PRACTICINGPRACTICE
Backend question · Node.js › Buffers & binary data

What does this log?

const buf = Buffer.from("abcdef");
const part = buf.subarray(0, 3);
part[0] = 0x7a; // "z"
console.log(buf.toString(), part.toString());
zbcdef zbc

The answer is zbcdef zbc.

subarray returns a view over the same memory, not a copy. The older buf.slice does the same. So writing to part also changes buf. To get an independent copy, use Buffer.from(part).

Shared memory has another effect: if you keep a tiny slice of a huge buffer, the whole huge allocation stays in memory.