4

I'm trying to read/write some binary data using the DataView object. It seems to work correctly when the buffer is initialized from a UInt8Array, however it if pass it a nodejs Buffer object the results seem to be off. Am I using the API incorrectly?


    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])
        let read = new DataView(arr.buffer).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);
      })

    })

The one with the buffer fails with

AssertionError: expected 1768779887 to equal 1437226410
      + expected - actual

      -1768779887
      +1437226410

3 Answers 3

3

Nodejs Buffer is just a view over underlying allocated buffer that can be a lot larger. This is how to get ArrayBuffer out of Buffer:

function getArrayBufferFromBuffer( buffer ) {
  return buffer.buffer.slice( buffer.byteOffset, buffer.byteOffset + buffer.byteLength ) );
}
Sign up to request clarification or add additional context in comments.

Comments

0

This helped (not sure if this is the most elegant):

const buff = Buffer.from(msgBody, 'base64');
let uint8Array = new Uint8Array(buff.length);
for(let counter=0;counter<buff.length;counter++) {
    uint8Array[counter] = buff[counter];
    //console.debug(`uint8Array[${counter}]=${uint8Array[counter]}`);
}
let dataview = new DataView(uint8Array.buffer, 0, uint8Array.length);

1 Comment

DataView should not only point to the length of the uint8array, but also the start offset of the underlying ArrayBuffer. This code may lead to bugs in production.
0

try use this buf.copy

const buf = fs.readFileSync(`...`);
const uint8arr = new Uint8Array(buf.byteLength);

buf.copy(uint8arr, 0, 0, buf.byteLength);
const v = new DataView(uint8arr.buffer);

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.