3

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 ]

1 Answer 1

2

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);

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

2 Comments

In case anyone else needs this: for the case where the buffer is retrieved using a fetch e.g const response = await fetch(bufferPath); const buffer = response.arrayBuffer() It seems new Uint16Array(buffer) will work
@Dianne Nice observation.

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.