demo · v140
Protocol Decoder
A length-prefixed binary protocol — every frame starts with a 4-byte big-endian length, then a 4-byte type, then payload. With min you can read the header in a single call: read(buf, {min: 8}). Then read exactly the payload bytes the header announced. No fragment reassembly.
// Length-prefixed frame decoder using min.
async function readFrame(reader) {
const hdr = new Uint8Array(8);
await reader.read(hdr, { min: 8 }); // single header read
const len = new DataView(hdr.buffer).getUint32(0, false);
const type = new DataView(hdr.buffer).getUint32(4, false);
const body = new Uint8Array(len);
await reader.read(body, { min: len }); // single body read
return { type, body };
}
pre-140 pain
Without min you'd build a "fill exactly N bytes" helper around a while loop — handling partial reads, leftover bytes, EOF mid-read. Cute the first time. Annoying when you have ten protocol types and each one needs custom unwinding for the EOF case.
see also
- BYOB min option — feature index