Base64-encode only a Uint8Array slice with Node.js Buffer
A three-byte view can accidentally encode a five-byte backing buffer. Compare copying the view with sharing its exact byte offset and length.
Inspect the range described by the view
Imagine a five-byte packet with markers AA and BB around a three-byte payload 00 FF 41. Calling subarray(1, 4) creates a view over the payload. Its buffer property still refers to the ArrayBuffer for the complete packet.
Compare a copy with a shared view
Buffer.from(payload) copies the bytes selected by this Uint8Array. Passing its backing buffer together with the offset and length shares that same range. The first log prints AP9B AP9B. The second prints 5 3 because the call using only payload.buffer spans the full packet.
const packet = Uint8Array.of(170, 0, 255, 65, 187);
const payload = packet.subarray(1, 4);
const copy = Buffer.from(payload);
const view = Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength);
console.log(copy.toString("base64"), view.toString("base64"));
console.log(Buffer.from(payload.buffer).length, copy.length);Account for later mutations
After running the snippet, set packet[1] = 1. The first byte of copy stays zero while the first byte of view becomes one. If encoding happens later from a queue, choose the copy or the shared view based on who might change the original bytes first.