在 nodejs 中以正确的方式写入和读取 typedArray

Writing and reading typedArray in nodejs the right way

我正在尝试将 Uint16Array 写入文件,然后使用 NodeJS 检索它,我成功了,但感觉我做错了。

"use strict";

const fs = require("fs").promises;

const A = new ArrayBuffer(20);
const a = new Uint16Array(A);

for(let i=0;i<a.length;++i){
    a[i]=i;
}

(async()=>{
    await fs.writeFile("test.txt",a,"binary")
    .catch((err)=>{console.error(err)});

    const buf = await fs.readFile("test.txt")
    .catch((err)=>{console.error(err)});

    const b = new Uint16Array((new Uint8Array(buf)).buffer);
    //^ feels wonky, like instead of just using the buf I have to
    //make a temporary Uint8Array of buf and then take its buffer
    //
    //if I don't do it this way b will be [0,1,0,2,0,3,0 ... etc]

    console.log("A=",A,"\na=",a);
    console.log("buffer=",buf,"\nb=",b);
})()

上面的代码有效并给出了以下结果:

它看起来不对,请注意我是如何将 b 变量设置为 Uint16Array 的,该 Uint16Array 由缓冲区的 Uint8Array 虚拟数组设置。我不想在那里有虚拟 Uint8Array。

在生产中,文件会更大,以兆字节为单位,我宁愿现在就做正确的事,也不愿以后再做。

“发生这种情况是因为 Buffer class 是 JavaScript 的 Uint8Array class 的子 class 而不是 Uint16Array 数组”

参考以下Whosebug...

更正:

 //const b =  new Uint16Array((new Uint8Array(buf)).buffer);
 //Change to this...
 const d = new Uint16Array(buf.buffer,buf.byteOffset,buf.length/2);

为了显示差异,我将其添加到您的代码中。

const b =  new Uint16Array((new Uint8Array(buf)).buffer);
const c = new Uint16Array(buf);
const d = new Uint16Array(buf.buffer,buf.byteOffset,buf.length/2);

//^ feels wonky, like instead of just using the buf I have to
//make a temporary Uint8Array of buf and then take its buffer
//
//if I don't do it this way b will be [0,1,0,2,0,3,0 ... etc]

console.log("A=",A,"\na=",a);
console.log("buffer=",buf,"\nb=",b);
console.log("buffer=",buf,"\nc=",c);
console.log("buffer=",buf,"\nd=",d);

这是结果....