Node.js Buffer 二进制字段实战:8 个实验读懂整数、大小端与记录边界

10-24 5阅读

把 Buffer 读写函数背下来,并不等于能正确解析二进制记录。真正容易漏掉的,是同一组字节的符号解释、字节序、完整字段边界,以及截取后的内存所有权。本文用八个相互独立的小程序逐项验证,再组合成一个有明确上限的记录编码器。

运行环境为 Node.js v24.19.0。每段代码完整保存为标注的 .cjs 文件,然后执行 node 加文件名即可,无第三方依赖。下面 stdout 来自实际运行,包含末尾换行;错误探针被程序主动捕获,所以正常运行应以零退出码结束。本文检验行为和边界,不做速度排名,也不把本地版本说成最新版本。

Node.js Buffer 二进制字段实战:8 个实验读懂整数、大小端与记录边界
模型生成的概念示意图,用于表现字节顺序和内存关系,不是软件截图,也不是逐字节布局图。

一、先确定字段宽度,再安排无符号整数

二进制数据本身不携带“这里是整数”的说明。写入前先约定字段宽度、字节序和起点。本例把一个八位值、一个十六位大端值、一个三十二位小端值放进七字节空间。每次写入方法返回下一个偏移位置,因此游标最后应等于总长度;这比到处手写常量更容易审查。

本文统一使用零填充的分配方式,让尚未写入的位置具有确定内容。每个实验只展示本次分配的字节,不依赖旧内存、随机数或机器路径,因此输出可逐行比较。对实际编码器而言,固定字段布局之后,还应把每个字段的写入位置列为测试对象。

无符号十六位的数学范围是零至六万五千五百三十五。第一次负向探针故意写入负一,实际被范围检查拒绝。这里保留错误名称和错误码,不绑定较长的英文报错句子。注意:越界值会怎样与“小数、字符串等不合约输入会怎样”是两个问题,业务入口仍应明确检查整数,不要把某次隐式转换当成协议承诺。

文件:01_unsigned.cjs;运行:node 01_unsigned.cjs。

"use strict";
const { Buffer } = require("node:buffer");
const assert = require("node:assert/strict");
const b = Buffer.alloc(7);
let p = b.writeUInt8(9, 0);
p = b.writeUInt16BE(50000, p);
p = b.writeUInt32LE(4000000000, p);
assert.equal(p, b.length);
console.log("hex", b.toString("hex"));
console.log("values", b.readUInt8(0), b.readUInt16BE(1), b.readUInt32LE(3));
try {
  b.writeUInt16BE(-1, 1); // Probe 1: unsigned negative value.
  assert.fail("expected rejection");
} catch (e) {
  assert.equal(e.code, "ERR_OUT_OF_RANGE");
  console.log("probe1", e.name, e.code);
}

实际 stdout:

hex 09c35000286bee
values 9 50000 4000000000
probe1 RangeError ERR_OUT_OF_RANGE

二、有符号解释会改变同一组字节的含义

有符号十六位整数的范围是负三万二千七百六十八至三万二千七百六十七,负数采用补码。我们把最小值、负一和最大值顺序写进去,再按原规则读回。负一的两个字节都是十六进制的 ff;改用无符号读取,得到的却是六万五千五百三十五。

第二次探针把上限再加一,验证不会自动替你表达更大的有符号值。因此,温度差值、增减量和计数器不能仅因为占用字节数相同,就随意交换读取函数。字段的符号属性应与宽度一起写进格式说明;调试时同时观察十六进制字节和解码后的十进制数,比只看其中一种更容易定位解释错误。

文件:02_signed.cjs;运行:node 02_signed.cjs。

"use strict";
const { Buffer } = require("node:buffer");
const assert = require("node:assert/strict");
const b = Buffer.alloc(6);
b.writeInt16LE(-32768, 0);
b.writeInt16LE(-1, 2);
b.writeInt16LE(32767, 4);
console.log("hex", b.toString("hex"));
console.log("signed", [0, 2, 4].map(p => b.readInt16LE(p)).join(","));
console.log("same-bytes-unsigned", b.readUInt16LE(2));
try {
  b.writeInt16LE(32768, 0); // Probe 2: one above signed maximum.
  assert.fail("expected rejection");
} catch (e) {
  assert.equal(e.code, "ERR_OUT_OF_RANGE");
  console.log("probe2", e.name, e.code);
}

实际 stdout:

hex 0080ffffff7f
signed -32768,-1,32767
same-bytes-unsigned 65535
probe2 RangeError ERR_OUT_OF_RANGE

三、大小端写错时,程序可能完全不报错

本例用不对称的十六进制数比较两种顺序:大端把高位字节放在前面,小端把低位字节放在前面。两段内存排列不同,但用匹配的方法读回,数值一致。这种显式方法不要求先判断当前处理器属于哪种字节序。

第三次探针只把解码方法从大端换成小端,不修改原始字节,得到另一个合法整数,并不会抛出异常。它是一次解码规则变异测试,不是输入越界测试。协议测试数据应包含这种各字节明显不同的值;全零、全一或者前后对称的字节,可能让错误的解码器也“通过”测试。

文件:03_endian.cjs;运行:node 03_endian.cjs。

"use strict";
const { Buffer } = require("node:buffer");
const assert = require("node:assert/strict");
const b = Buffer.alloc(8);
b.writeUInt32BE(0x12345678, 0);
b.writeUInt32LE(0x12345678, 4);
console.log("hex", b.toString("hex"));
console.log("matching", b.readUInt32BE(0), b.readUInt32LE(4));
const wrong = b.readUInt32LE(0); // Probe 3: mutate the decoding rule.
assert.notEqual(wrong, 0x12345678);
console.log("probe3-wrong-endian", wrong, wrong.toString(16));

实际 stdout:

hex 1234567878563412
matching 305419896 305419896
probe3-wrong-endian 2018915346 78563412

四、三字节与六字节字段,用可变宽度方法

某些文件头会使用二十四位长度或四十八位标识,不必先拆成多个位运算。本例在前三字节写入一个大端值,后六字节写入四十八位无符号上限,再分别读回。输出说明字段宽度也参与解释,不能只记住起始偏移。

这里的可变宽度整数接口接受一至六字节。第四次探针请求七字节,即使目标缓冲区的总空间足够,仍会失败:这是接口支持宽度的限制,不是内存不够。不要为了装下六十四位整数而把宽度参数继续加大,后面的 BigInt 专用方法才是对应选择。

文件:04_variable_width.cjs;运行:node 04_variable_width.cjs。

"use strict";
const { Buffer } = require("node:buffer");
const assert = require("node:assert/strict");
const b = Buffer.alloc(9);
b.writeUIntBE(0xabcdef, 0, 3);
b.writeUIntLE(2 ** 48 - 1, 3, 6);
console.log("hex", b.toString("hex"));
console.log("values", b.readUIntBE(0, 3), b.readUIntLE(3, 6));
try {
  b.writeUIntBE(1, 0, 7); // Probe 4: unsupported field width.
  assert.fail("expected rejection");
} catch (e) {
  assert.equal(e.code, "ERR_OUT_OF_RANGE");
  console.log("probe4", e.name, e.code);
}

实际 stdout:

hex abcdefffffffffffff
values 11259375 281474976710655
probe4 RangeError ERR_OUT_OF_RANGE

五、偏移检查的是整个字段,而不是起点一个字节

一个六字节缓冲区中,四字节字段的最后合法起点是二,而不是五。检查条件可写成:偏移为非负整数,并且偏移不超过总长度减字段宽度。本例先在最后合法起点成功写入并读取,接着把读取起点向后移动一字节。

请把偏移看成从零开始的字节坐标,而不是第几个业务元素。一个四字节字段向后移动一格,偏移应增加四;字符串字符数量、数组元素数量与二进制字节长度也不能混用。样本代码刻意把字段放在非零起点,避免所有用例都从零读取而掩盖偏移计算问题。

第五次探针触发越界错误。这种边界最常出现在网络包截断或文件尾部不足时。接收端应在解释字段前验证剩余长度,不能依赖“起点仍在数组里”就开始读。对于变长消息,还必须单独核对声明长度与实际长度,否则截断错误可能被误归类为业务值异常。

文件:05_offsets.cjs;运行:node 05_offsets.cjs。

"use strict";
const { Buffer } = require("node:buffer");
const assert = require("node:assert/strict");
const b = Buffer.alloc(6);
b.writeUInt32BE(0x01020304, 2);
console.log("hex", b.toString("hex"));
console.log("last-valid-offset", b.length - 4, b.readUInt32BE(2));
try {
  b.readUInt32BE(3); // Probe 5: field extends one byte past the end.
  assert.fail("expected rejection");
} catch (e) {
  assert.equal(e.code, "ERR_OUT_OF_RANGE");
  console.log("probe5", e.name, e.code);
}

实际 stdout:

hex 000001020304
last-valid-offset 2 16909060
probe5 RangeError ERR_OUT_OF_RANGE

六、六十四位字段全程使用 BigInt

有符号六十四位范围是负的二的六十三次方至二的六十三次方减一,无符号范围是零至二的六十四次方减一。本例分别写入有符号两端和无符号上限,常量、位移与计算都使用带 n 的 BigInt,打印时再转成十进制字符串。

第六次探针写入二的六十四次方,验证无符号上限之外的值被拒绝。不要先把大整数放进 Number 再转换回来,已经损失的精度无法补救。若接口用 JSON 交换这些字段,可以约定十进制字符串,并在接收端验证格式和范围;字符串只是传输表示,进入本例编码器之前仍需明确转换为 BigInt。

文件:06_bigint64.cjs;运行:node 06_bigint64.cjs。

"use strict";
const { Buffer } = require("node:buffer");
const assert = require("node:assert/strict");
const b = Buffer.alloc(24);
b.writeBigInt64BE(-(1n << 63n), 0);
b.writeBigInt64LE((1n << 63n) - 1n, 8);
b.writeBigUInt64BE((1n << 64n) - 1n, 16);
console.log("hex", b.toString("hex"));
console.log("signed-min", b.readBigInt64BE(0).toString());
console.log("signed-max", b.readBigInt64LE(8).toString());
console.log("unsigned-max", b.readBigUInt64BE(16).toString());
try {
  b.writeBigUInt64BE(1n << 64n, 16); // Probe 6: unsigned overflow.
  assert.fail("expected rejection");
} catch (e) {
  assert.equal(e.code, "ERR_OUT_OF_RANGE");
  console.log("probe6", e.name, e.code);
}

实际 stdout:

hex 8000000000000000ffffffffffffff7fffffffffffffffff
signed-min -9223372036854775808
signed-max 9223372036854775807
unsigned-max 18446744073709551615
probe6 RangeError ERR_OUT_OF_RANGE

七、截取视图不是复制,修改会传回源缓冲区

我们从三个十六位字段中截取中间一个。subarray 的起点包含、终点不包含,得到的视图长度为二,但它与源缓冲区共享对应的内存。为了建立真正独立的快照,本例另行分配同样长度,再调用 copy 把字节复制进去。

第七次探针通过视图写入九百九十九,源对象中间字段同步改变,独立副本仍保留二百。视图可用于原地修改,但不适合被误当作历史快照。如果后续逻辑会复用接收缓冲区,存档、异步处理或交给其他模块前,应明确选择共享还是复制;单纯换一个变量名不会建立隔离。

文件:07_alias_copy.cjs;运行:node 07_alias_copy.cjs。

"use strict";
const { Buffer } = require("node:buffer");
const assert = require("node:assert/strict");
const source = Buffer.alloc(6);
source.writeUInt16BE(100, 0);
source.writeUInt16BE(200, 2);
source.writeUInt16BE(300, 4);
const view = source.subarray(2, 4);
const copy = Buffer.alloc(view.length);
view.copy(copy);
console.log("before", source.toString("hex"), copy.toString("hex"));
view.writeUInt16BE(999, 0); // Probe 7: mutate a shared view.
assert.equal(source.readUInt16BE(2), 999);
assert.equal(copy.readUInt16BE(0), 200);
console.log("probe7-source", source.toString("hex"));
console.log("probe7-view-copy", view.readUInt16BE(0), copy.readUInt16BE(0));

实际 stdout:

before 006400c8012c 00c8
probe7-source 006403e7012c
probe7-view-copy 999 200

八、把规则合起来:最多四个样本的有界记录

下面自定义一个教学格式:偏移 0、1 处是大端魔数 BR,偏移 2 是版本,偏移 3 是样本数;偏移 4 至 7 存小端序号,偏移 8 至 15 存大端无符号六十四位标识。从偏移 16 起,每个样本占两个字节,按小端有符号整数处理。它只是本例格式,不声称兼容任何现成协议。

编码器先验证序号、标识、样本数组和每个元素,全部通过后才分配内存。样本数只允许零至四,记录总长因此限定在十六至二十四字节。解码器依次检查类型、总大小、魔数、版本、样本数量和精确长度,之后才读取样本。精确长度同时拒绝少字节和多余尾部,避免同一输入存在两种解释。

正常往返使用一个超过 Number 安全整数上限的标识,断言结果与原对象一致。第八次探针删去最后一个载荷字节,长度仍落在总大小范围内,却不再匹配声明数量,实际在读取样本前被拒绝。示例返回独立的数字数组,不把内部载荷视图交给调用方,减少共享可变状态。

文件:08_bounded_record.cjs;运行:node 08_bounded_record.cjs。

"use strict";
const { Buffer } = require("node:buffer");
const assert = require("node:assert/strict");
const HEADER = 16;
const MAX_SAMPLES = 4;
const MAX_ID = (1n << 64n) - 1n;
function integer(value, min, max, name) {
  if (!Number.isInteger(value) || value < min || value > max) {
    throw new RangeError(name + " out of range");
  }
}
function encode(record) {
  if (!record || typeof record !== "object") throw new TypeError("record required");
  const { sequence, id, samples } = record;
  integer(sequence, 0, 0xffffffff, "sequence");
  if (typeof id !== "bigint" || id < 0n || id > MAX_ID) {
    throw new RangeError("id out of range");
  }
  if (!Array.isArray(samples)) throw new TypeError("samples must be an array");
  integer(samples.length, 0, MAX_SAMPLES, "sample count");
  for (const sample of samples) integer(sample, -32768, 32767, "sample");
  const b = Buffer.alloc(HEADER + samples.length * 2);
  b.writeUInt16BE(0x4252, 0); // Magic: BR.
  b.writeUInt8(1, 2);         // Version.
  b.writeUInt8(samples.length, 3);
  b.writeUInt32LE(sequence, 4);
  b.writeBigUInt64BE(id, 8);
  samples.forEach((sample, i) => b.writeInt16LE(sample, HEADER + i * 2));
  return b;
}
function decode(b) {
  if (!Buffer.isBuffer(b)) throw new TypeError("Buffer required");
  if (b.length < HEADER || b.length > HEADER + MAX_SAMPLES * 2) {
    throw new RangeError("record size out of range");
  }
  if (b.readUInt16BE(0) !== 0x4252 || b.readUInt8(2) !== 1) {
    throw new Error("unsupported record");
  }
  const count = b.readUInt8(3);
  integer(count, 0, MAX_SAMPLES, "sample count");
  if (b.length !== HEADER + count * 2) throw new RangeError("length mismatch");
  const samples = [];
  for (let i = 0; i < count; i++) samples.push(b.readInt16LE(HEADER + i * 2));
  return { sequence: b.readUInt32LE(4), id: b.readBigUInt64BE(8), samples };
}
const input = { sequence: 7, id: 9007199254740993n, samples: [-300, 1200] };
const bytes = encode(input);
const output = decode(bytes);
assert.deepEqual(output, input);
console.log("hex", bytes.toString("hex"));
console.log("record", output.sequence, output.id.toString(), output.samples.join(","));
try {
  decode(bytes.subarray(0, bytes.length - 1)); // Probe 8: truncated payload.
  assert.fail("expected rejection");
} catch (e) {
  assert.equal(e.message, "length mismatch");
  console.log("probe8", e.name, e.message);
}

实际 stdout:

hex 42520102070000000020000000000001d4feb004
record 7 9007199254740993 -300,1200
probe8 RangeError length mismatch

落地前的检查清单

本轮八个探针中,六个刻意触发拒绝,分别是负数写入无符号字段、有符号溢出、七字节宽度、字段跨界、六十四位溢出和载荷截断;另外两个验证错误字节序和共享视图写入。它们与正常往返检查一起构成最小回归用例,不等于对所有非法输入的穷尽测试。

实际接入文件或网络数据时,把字段约定、容量上限和内存所有权一并写在接口旁边。这里尚未处理分包重组、校验和、身份认证与版本升级;这些需求应在传输层和协议层继续设计,不能因为整数能够读回,就认定整条通信链路已经可靠。

官方参考

以下均为 Node.js v24.19.0 固定版本文档;示例与输出为本文独立编写并实测。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。