Buffer slicing and numeric reads
Local practice: Node.js 22.16.0 and npm 10.9.2 on Linux x64; proposed teaching baseline 26.13.1 LTS remains untested. Use a fresh disposable folder for each example, copy only the shown files and run the fixed command. No packages or external services required. Static examples are not ByteMind runner support. The archive is author-only; do not copy expected.json into the example directory.
Compare shared views and copies
import { Buffer } from "node:buffer";const original = Buffer.from([10, 20, 30]);const view = original.subarray(1, 3);const copy = Buffer.from(view);view[0] = 99;console.log(JSON.stringify([...original]));console.log(JSON.stringify([...copy]));Run in this fixture directory:
node main.mjsExpected stdout:
[10,99,30][20,30]Expected exit status: 0. Expected stderr: empty. The view changes the original; the copied bytes preserve the earlier values.
How it works
buf.subarray(start, end) uses an exclusive end index and shares backing storage. The legacy Buffer.slice also shares storage, unlike ordinary TypedArray.slice; prefer subarray for clarity. Buffer.from(view) copies the bytes when view is a Buffer. readUInt16BE(offset) interprets two bytes as an unsigned big-endian integer; readUInt16LE interprets the same bytes in little-endian order. Verify bounds before reading data of unknown length. Buffer.concat combines buffers into a new buffer, useful for small bounded pieces; avoid repeatedly concatenating unbounded streams.
Read a bounded binary header
import { Buffer } from "node:buffer";const bytes = Buffer.from([0x01, 0x02]);console.log(bytes.readUInt16BE(0), bytes.readUInt16LE(0));const short = Buffer.from([1]);console.log(short.length >= 2 ? short.readUInt16BE(0) : "incomplete header");Run in this fixture directory:
node main.mjsExpected stdout:
258 513incomplete headerExpected exit status: 0. Expected stderr: empty. Big endian uses 1 × 256 + 2; little endian reverses the weights. The short record is rejected before reading.
Common mistake
Do not assume modifying a subarray leaves the original unchanged. If an independent snapshot is required, copy the view explicitly. Do not choose endian order based on host CPU alone; follow the file or protocol format.
Try it yourself
Use bytes [0x00, 0x10] and compute their unsigned 16-bit value in both orders. Copy a subarray, change the copy and confirm the original stays the same.
Further reading: Official documentation 1. Related ByteMind reference candidate: node-buffer-subarray (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Buffer slicing and numeric reads — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What does changing a Buffer subarray do?
Which byte order reads [1,2] as 258?
How do you make a separate copy of a Buffer view?