Home > Enterprise >  Read/Write a typed array to file with node.js
Read/Write a typed array to file with node.js

Time:11-01

I have the following typed array: Uint16Array(2) [ 60891, 11722 ] which I would like to save to a (binary) file. I would then like to read it back into another Uint16Array with the order of the elements preserved.

I tried using the fs module but when I go to read the file I'm not getting the same integers:

//console.log(buffer) : Uint16Array(2) [ 60891, 11722 ]
fs.writeFileSync(bufferPath, buffer, 'binary')
const loadedBuffer = fs.readFileSync(bufferPath)
//console.log(new Uint16Array(loadedBuffer)) : Uint16Array(4) [ 219, 237, 202, 45 ]

CodePudding user response:

This happens because the Buffer class is a subclass of JavaScript's Uint8Array class and not a Uint16Array array as you commented in your code. To obtain a copy of the original Uint16Array array you can use the new Uint16Array(buffer, byteOffset, length) constructor like mentioned in the Uint16Array documentation:

let arr = new Uint16Array(loadedBuffer.buffer, loadedBuffer.byteOffset, loadedBuffer.length / 2);

  • Related