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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Not sure what you mean here. Yes, Buffer is also Uint8Array - but you don't have to use it as former.
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 overhead
Yes, and that's also mentioned in the docs. Inheritance in this case means also overriding some methods' behaviour.

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.