实现说明
Buffer 来自 node:buffer——Node.js 随运行时自带的核心模块。
各个操作都建立在顶层绑定之上:frame16、frame32、odd。
使用要点
node:buffer是 Node.js 内建模块——随运行时自带,无需安装。- 每一步打印都带着自己的标签:
swap16 hex:、swap32 hex:、unaligned:。
常见问题
需要安装第三方包吗?
不需要——node:buffer 是 Node.js 内建模块,无需安装。
核心语句
const frame16 = Buffer.from([0x01, 0x02, 0x03, 0x04]);
const frame32 = Buffer.from([0x12, 0x34, 0x56, 0x78]);
const odd = Buffer.from([0xaa, 0xbb, 0xcc]);
代码示例
import { Buffer } from 'node:buffer';
// Big-endian 16-bit header pairs: 0x0102, 0x0304
const frame16 = Buffer.from([0x01, 0x02, 0x03, 0x04]);
frame16.swap16();
console.log('swap16 hex:', frame16.toString('hex'), 'LE[0]:', frame16.readUInt16LE(0).toString(16));
// Big-endian 32-bit integer 0x12345678 swapped in place to little-endian
const frame32 = Buffer.from([0x12, 0x34, 0x56, 0x78]);
frame32.swap32();
console.log('swap32 hex:', frame32.toString('hex'), 'LE:', frame32.readUInt32LE(0).toString(16));
// Unaligned lengths throw RangeError instead of silently truncating trailing bytes
const odd = Buffer.from([0xaa, 0xbb, 0xcc]);
try {
odd.swap16();
} catch (err) {
console.log('unaligned:', err.name, err.code);
}