实现说明
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'));