gpt4 book ai didi

arrays - nodejs从缓冲区数据到字节数组的转换

转载 作者:搜寻专家 更新时间:2023-10-31 22:30:24 24 4
gpt4 key购买 nike

我想将缓冲区数据转换为字节数组。这是我试过的

import * as fs from 'fs';
[...]
event:(data) => {
fs.readFile(data, function(err, data) {
var arrByte= new Uint8Array(data)
var binaryData= new Blob([arrByte])
console.log(binaryData)
}
}

我还没有完成这项工作,因此我发表了这篇文章。我非常想知道我在做什么是不对的。

最佳答案

Buffer docs are very enlightening :

Prior to the introduction of TypedArray, the JavaScript language had no mechanism for reading or manipulating streams of binary data. The Buffer class was introduced as part of the Node.js API to enable interaction with octet streams in TCP streams, file system operations, and other contexts.

With TypedArray now available, the Buffer class implements the Uint8Array API in a manner that is more optimized and suitable for Node.js.

Buffer instances are also Uint8Array instances. However, there are subtle incompatibilities with TypedArray. For example, while ArrayBuffer#slice() creates a copy of the slice, the implementation of Buffer#slice() creates a view over the existing Buffer without copying, making Buffer#slice() far more efficient.

It is also possible to create new TypedArray instances from a Buffer with the following caveats:

  1. The Buffer object's memory is copied to the TypedArray, not shared.

  2. The Buffer object's memory is interpreted as an array of distinct elements, and not as a byte array of the target type. That is, new Uint32Array(Buffer.from([1, 2, 3, 4])) creates a 4-element Uint32Array with elements [1, 2, 3, 4], not a Uint32Array with a single element [0x1020304] or [0x4030201].

他们继续提到 TypedArray.from ,它在 Node 中接受 Buffer,所以“正确”的方式是:

var arrByte = Uint8Array.from(data)

...然而,这根本不是必需的,因为 BufferUint8Arraynew UintArray(someBuffer) 确实工作得很好。

您的问题中也没有上下文,但是 Blob 不存在于 Node 中,无论如何您都不需要它,因为 Buffer 已经为您提供了原始访问权限二进制数据和其他 fs 方法可让您读取和写入文件。

关于arrays - nodejs从缓冲区数据到字节数组的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51511307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com