← 中文资源

简体中文版本

Buffer 在显式字节偏移读写

Buffer 的读写方法都带字节偏移参数:魔数、版本、标志、有符号字节各占固定位,write 后 read 逐字段还原,hex 输出与二进制布局一一对应。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

Buffer 来自 node:buffer——Node.js 随运行时自带的核心模块。 header 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 无需安装:node:buffer 随 Node.js 本体提供。
  • 每一步打印都带着自己的标签:version:、signed :。

常见问题

导入的模块是 npm 包吗?

不需要——node:buffer 内置于 Node.js。node: 前缀就代表核心模块,项目里无需添加任何东西。

核心语句

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);

代码示例

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'));