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

1

3

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.

Implacable answered 3/5, 2017 at 20:5 Comment(0)
A
6

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.

Abyssinia answered 3/5, 2017 at 20:8 Comment(4)
But why would someone ever need the uInt8Array? You read a file directly into a buffer and deal with bytes? If you read in a binary file the chance of it being all being uInt8 seems slim and just adds overhead, and in my case confusion and frustration.Implacable
Not sure what you mean here. Yes, Buffer is also Uint8Array - but you don't have to use it as former.Abyssinia
I'm confused too;) buffer doesnt seem to also be a uint8Array because the uint8Array.slice(266,length) gives me the Uint8array Indexes so its twice as much, where the buffer slice slices single bytes. Just seems like added overheadImplacable
Yes, and that's also mentioned in the docs. Inheritance in this case means also overriding some methods' behaviour.Abyssinia

© 2022 - 2024 — McMap. All rights reserved.