Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DataView with nodejs Buffer

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
like image 305
Danny Avatar asked Oct 24 '25 16:10

Danny


1 Answers

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 ) );
}
like image 139
Riad Baghbanli Avatar answered Oct 26 '25 06:10

Riad Baghbanli