Buffer Read Write At Explicit Offsets

Buffer write and read methods take a byte offset argument, so wire-format headers place each field at a fixed home and round-trip exactly.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
import { Buffer } from 'node:buffer';

// Byte offsets are the contract: every field has a fixed home in the buffer
const header = Buffer.alloc(8);

header.writeUInt32BE(0x00af3c11, 0); // magic at offset 0
header.writeUInt16BE(7, 4); // version at offset 4
header.writeUInt8(0x7f, 6); // flags at offset 6
header.writeInt8(-1, 7); // signed byte at offset 7

console.log('magic  :', header.readUInt32BE(0));
console.log('version:', header.readUInt16BE(4));
console.log('flags  :', header.readUInt8(6));
console.log('signed :', header.readInt8(7));
console.log('hex    :', header.toString('hex'));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

magic  : 11484177
version: 7
flags  : 127
signed : -1
hex    : 00af3c1100077fff

Inside the snippet

The import names the platform contact area: Buffer, all from node:buffer.

Top-level bindings header hold the demo state — nothing sits inside a function scope.

Watch out for

  • node:buffer is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Putting it to use

The demo output is labeled (magic :, version:, flags :), so every printed line maps back to its originating operation.

Core lines

header.writeUInt32BE(0x00af3c11, 0); // magic at offset 0
header.writeUInt16BE(7, 4); // version at offset 4
header.writeUInt8(0x7f, 6); // flags at offset 6
header.writeInt8(-1, 7); // signed byte at offset 7
console.log('magic  :', header.readUInt32BE(0));
const header = Buffer.alloc(8);

Interactive Tools for This Topic

FAQ

Is the imported module an npm package?
No — `node:buffer` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.