我正在尝试将一个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的,它是由缓冲区的虚拟Uint8Array数组设置的。我不想让假的Uint8Array在里面。
在生产中,文件会大得多,按照兆字节的顺序,我宁愿现在就做正确的事情,而不是以后。
发布于 2022-05-25 19:23:03
“这是因为缓冲区类是JavaScript的Uint8Array类的子类,而不是Uint16Array数组的子类”
参考下面的堆栈溢出..。读取/写入类型化数组以使用node.js进行文件
纠正:
//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);
这是结果..。
https://stackoverflow.com/questions/69780111
复制相似问题