首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用nodejs编写和读取typedArray的正确方法

用nodejs编写和读取typedArray的正确方法
EN

Stack Overflow用户
提问于 2021-10-30 13:36:50
回答 1查看 262关注 0票数 0

我正在尝试将一个Uint16Array写到一个文件中,然后用NodeJS检索它,我是成功的,但感觉好像我做错了。

代码语言:javascript
运行
复制
"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在里面。

在生产中,文件会大得多,按照兆字节的顺序,我宁愿现在就做正确的事情,而不是以后。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-25 19:23:03

“这是因为缓冲区类是JavaScript的Uint8Array类的子类,而不是Uint16Array数组的子类”

参考下面的堆栈溢出..。读取/写入类型化数组以使用node.js进行文件

纠正:

代码语言:javascript
运行
复制
 //const b =  new Uint16Array((new Uint8Array(buf)).buffer);
 //Change to this...
 const d = new Uint16Array(buf.buffer,buf.byteOffset,buf.length/2);

为了显示不同之处,我将其添加到代码中。

代码语言:javascript
运行
复制
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);

这是结果..。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69780111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档