Node.js中DataView操作Buffer读取二进制数据异常问题排查
Ah, I see the issue here! The problem isn’t that you’re misusing the API directly, but that Node.js Buffer instances have a subtle difference from vanilla Uint8Array when it comes to their underlying ArrayBuffer.
Here’s what’s happening: Node.js uses a buffer pool for small allocations (like your 20-byte example). When you create a Buffer.from([...]), instead of allocating a brand-new ArrayBuffer just for your data, Node.js slices a chunk from a pre-allocated pool. That means your Buffer instance’s buffer property points to the entire pool, not just your 20 bytes of data. Your actual values start at arr.byteOffset within that pool, not at offset 0.
In contrast, when you create a Uint8Array directly from an array, it gets its own dedicated ArrayBuffer where your data starts at offset 0—so using arr.buffer works exactly as you expect.
To fix the Buffer test case, you need to pass the byteOffset and byteLength to the DataView constructor, so it only interacts with the portion of the ArrayBuffer that belongs to your Buffer:
import { expect } from 'chai'; describe('read binary data', () => { it('test buffer', () => { let arr = Buffer.from([0x55,0xaa,0x55,0xaa,0x60,0x00,0x00,0x00,0xd4,0x03,0x00,0x00,0x1c,0xd0,0xbb,0xd3,0x00,0x00,0x00,0x00]) // Target only the Buffer's slice of the underlying ArrayBuffer let read = new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint32(0, false); expect(read).to.eq(0x55aa55aa); }) it('test uint8array', () => { let arr = new Uint8Array([0x55,0xaa,0x55,0xaa,0x60,0x00,0x00,0x00,0xd4,0x03,0x00,0x00,0x1c,0xd0,0xbb,0xd3,0x00,0x00,0x00,0x00]) let read = new DataView(arr.buffer).getUint32(0, false); expect(read).to.eq(0x55aa55aa); }) })
This tells DataView to start reading from the correct offset in the pool and only access the length of your Buffer instance. Now both test cases should pass.
If you log arr.byteOffset for your Buffer instance, you’ll see it’s not 0 (the exact value depends on the current state of Node.js’s buffer pool), which explains why reading from offset 0 of the full pool gave you that unexpected number.
内容的提问来源于stack exchange,提问作者Danny

