Append bytes to a resizable ArrayBuffer
Append bytes to a resizable ArrayBuffer, keep its Uint8Array view live, and enforce the maximum size before growing the buffer.
A binary file arrives in chunks and you need the bytes together for a parser. With a fixed-size buffer, a grow operation means allocating a bigger buffer and copying the bytes you've collected so far. A resizable ArrayBuffer lets your code keep the same buffer and append at the old end.
Grow before writing the next chunk
Give the buffer an initial length of zero and a maximum of eight bytes for this example. Create a Uint8Array over the buffer without passing a view length.
const buffer = new ArrayBuffer(0, { maxByteLength: 8 });
const bytes = new Uint8Array(buffer);
function append(chunk) {
const offset = buffer.byteLength;
const nextLength = offset + chunk.byteLength;
if (nextLength > buffer.maxByteLength) {
throw new RangeError("Byte limit exceeded");
}
buffer.resize(nextLength);
bytes.set(chunk, offset);
}
append(Uint8Array.of(10, 20));
append(Uint8Array.of(30));
console.log(bytes.length, [...bytes]);Save the example as append.mjs and run node append.mjs on Node 22. It prints 3 [ 10, 20, 30 ]. The original view covers the new length after both calls.
Call resize before set so the write fits inside the view. The buffer keeps its identity and the previous bytes stay accessible in their original positions. The runtime controls the allocation, so the code avoids an explicit copy of the accumulated bytes without making a guarantee about what the engine does.
Keep the view length automatic
A view made with new Uint8Array(buffer) follows the buffer length. If you make new Uint8Array(buffer, 0, 2) after the first append, that view covers two bytes. After the next append, it still covers two. Pass the explicit length when you need a fixed window on a header or another known slice of the buffer.
In the example, byteLength is both the end of the data and the size of the buffer. If you start growing in larger steps to accommodate small appends, keep a separate count of bytes written. Use that count as the next write offset.
Choose the maximum based on the largest input your parser should accept. Stop the read when an append crosses it. In a runtime without ArrayBuffer.prototype.resize, use the same cap on the allocate-and-copy path so the input limit holds either way.