Node fs.readFileSync returns a uInt8 array instead of raw buffer array?

arrays, binary, node.js, strong-typing

Solution

Because since v3.0.0 `Buffer` class inherits from `Uint8Array` class. Quoting the doc:

`Buffer` instances are also `Uint8Array` instances. However, there are subtle incompatibilities with the `TypedArray` specification in ECMAScript 2015. For example, while `ArrayBuffer#slice()` creates a copy of the slice, the implementation of `Buffer#slice()` creates a view over the existing `Buffer` without copying, making `Buffer#slice()` far more efficient. [...]

It is possible to create a new `Buffer` that shares the same allocated memory as a `TypedArray` instance by using the `TypeArray` object's `.buffer` property.

... which is exactly what's done in your example.

Problem

why is this: ``` var myArrayBuffer = fs.readFileSync(file, null) ``` returning an uInt8 array instead of a just a arrayBuffer? why does this seem to work? ``` var myArrayBuffer = fs.readFileSync(file, null).buffer; var myAArray = new Uint16Array( myArrayBuffer.slice(266,(sizeofArray*sizeOfArrayElement)); ``` Why would the fs.readFile parse my file into a uInt8 array? Makes no sense, the file has a bunch of different datatypes that are not 1 byte long.

Original source