Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 665
LrakWortep Avatar asked Mar 16 '26 13:03

LrakWortep


1 Answers

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.

like image 106
raina77ow Avatar answered Mar 19 '26 02:03

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!