Read/Write 用 node.js 归档的类型化数组

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

我有以下类型化数组:Uint16Array(2) [ 60891, 11722 ] 我想将其保存到(二进制)文件中。然后我想将它读回另一个 Uint16Array 并保留元素的顺序。

我尝试使用 fs 模块,但是当我去阅读文件时,我没有得到相同的整数:

//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 ]

发生这种情况是因为 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 文档:

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