0

I have encountered a very weird behavior I do not understand after trying to debug my application for half a day. Have a look at the following snippet:

const buffer = Buffer.from([12, 34, 56, 78, 90]);
const dataView = new DataView(buffer.buffer);

console.log('buffer byteLength:', buffer.byteLength);
console.log('dataView byteLength:', dataView.byteLength);

console.log('first uint8 in buffer:', buffer.readUInt8(0));
console.log('first uint8 in dataView:', dataView.getUint8(0));

For me, the output of this script is:

buffer byteLength: 5
dataView byteLength: 8192
first uint8 in buffer: 12
first uint8 in dataView: 99

The Node.js version I used is 8.6.0.

Neonit
  • 542
  • 9
  • 22

1 Answers1

0

Apparently, despite not noted in the official documentation of Buffer.from, the function automatically creates a Buffer with unsafe allocation, described in the documentation of Buffer.allocUnsafe().

There is an answer on StackOverflow hinting that there is a property Buffer#byteOffset holding the byte offset for the Buffer's underlying ArrayBuffer. This property is not documented for Buffer itself, but for Uint8Array, whose API Buffer implements.

Extending the original snippet with the following line will produce the expected output.

console.log('first uint8 in dataView:', dataView.getUint8(buffer.byteOffset)); // output: 12
Neonit
  • 542
  • 9
  • 22