如何将一个NodeJS二进制缓冲区转换为JavaScript数组缓冲区?
当前回答
Buffer是ArrayBuffer的视图。你可以使用buffer属性访问内部包装的ArrayBuffer。
这是共享内存,不需要复制。
const arrayBuffer = theBuffer.buffer
如果你想要数据的副本,从原始的Buffer(不是从包装的ArrayBuffer)创建另一个Buffer,然后引用它的包装的ArrayBuffer。
const newArrayBuffer = Buffer.from(theBuffer).buffer
作为参考,从另一个方向,从ArrayBuffer到Buffer
const arrayBuffer = getArrayBuffer()
const sharedBuffer = Buffer.from(arrayBuffer)
const copiedBuffer = Buffer.from(sharedBuffer)
const copiedArrayBuffer = copiedBuffer.buffer
其他回答
一种更快的写法
var arrayBuffer = new Uint8Array(nodeBuffer).buffer;
然而,在包含1024个元素的缓冲区上,这似乎比建议的toArrayBuffer函数慢了大约4倍。
Buffer是ArrayBuffer的视图。你可以使用buffer属性访问内部包装的ArrayBuffer。
这是共享内存,不需要复制。
const arrayBuffer = theBuffer.buffer
如果你想要数据的副本,从原始的Buffer(不是从包装的ArrayBuffer)创建另一个Buffer,然后引用它的包装的ArrayBuffer。
const newArrayBuffer = Buffer.from(theBuffer).buffer
作为参考,从另一个方向,从ArrayBuffer到Buffer
const arrayBuffer = getArrayBuffer()
const sharedBuffer = Buffer.from(arrayBuffer)
const copiedBuffer = Buffer.from(sharedBuffer)
const copiedArrayBuffer = copiedBuffer.buffer
可以把ArrayBuffer看作是类型化的Buffer。
因此,ArrayBuffer总是需要一个类型(所谓的“数组缓冲区视图”)。通常,数组缓冲区视图有Uint8Array或Uint16Array类型。
Renato Mangini有一篇关于ArrayBuffer和String之间转换的好文章。
我在一个代码示例中总结了基本部分(用于Node.js)。它还展示了如何在类型化的ArrayBuffer和非类型化的Buffer之间进行转换。
function stringToArrayBuffer(string) {
const arrayBuffer = new ArrayBuffer(string.length);
const arrayBufferView = new Uint8Array(arrayBuffer);
for (let i = 0; i < string.length; i++) {
arrayBufferView[i] = string.charCodeAt(i);
}
return arrayBuffer;
}
function arrayBufferToString(buffer) {
return String.fromCharCode.apply(null, new Uint8Array(buffer));
}
const helloWorld = stringToArrayBuffer('Hello, World!'); // "ArrayBuffer" (Uint8Array)
const encodedString = new Buffer(helloWorld).toString('base64'); // "string"
const decodedBuffer = Buffer.from(encodedString, 'base64'); // "Buffer"
const decodedArrayBuffer = new Uint8Array(decodedBuffer).buffer; // "ArrayBuffer" (Uint8Array)
console.log(arrayBufferToString(decodedArrayBuffer)); // prints "Hello, World!"
"From ArrayBuffer to Buffer"可以这样做:
var buffer = Buffer.from( new Uint8Array(arrayBuffer) );
这个代理将把缓冲区暴露为任何typedarray,没有任何副本。:
https://www.npmjs.com/package/node-buffer-as-typedarray
它只能在LE上工作,但是可以很容易地移植到be上。 而且,从来没有真正测试过这有多高效。