Example 1 — Lock a Finished Buffer at Its Exact Size
Build data in a growable buffer, then lock it at its exact size before storing it or passing it on.
const draft = new ArrayBuffer(4, { maxByteLength: 64 });
const bytes = new Uint8Array(draft);
bytes.set([7, 8, 9]);
const finished = draft.transferToFixedLength(3);
console.log(finished.byteLength); // 3
console.log(finished.resizable); // false
console.log(JSON.stringify(Array.from(new Uint8Array(finished)))); // [7,8,9]
console.log(draft.detached); // true How It Works
- Draft in a growable buffer.
drafthas 4 bytes of room (and could grow to 64), but only 3 bytes hold data. - Trim and lock in one step.
transferToFixedLength(3)drops the unused fourth byte and returns a buffer whose size can never change. - The draft is retired. The bytes now live in
finished;draftis detached, so nothing can keep writing to the old buffer.

