天天看点

Buffer.from(arrayBuffer[, byteOffset[, length]])

Buffer.from(arrayBuffer[, byteOffset[, length]])

  • arrayBuffer - 一个 TypedArray 或 new ArrayBuffer() 的 .buffer 属性
  • byteOffset {Number} 默认:0
  • length {Number} 默认:arrayBuffer.length - byteOffset

当传递的是 TypedArray 实例的 .buffer 引用时,这个新建的 Buffer 将像 TypedArray 那样共享相同的内存分配。

const arr = new Uint16Array(2);     arr[0] = 5000;     arr[1] = 4000;     const buf = Buffer.from(arr.buffer); // shares the memory with arr;     console.log(buf);     // Prints: <Buffer 88 13 a0 0f>     // changing the TypedArray changes the Buffer also     arr[1] = 6000;     console.log(buf);     // Prints: <Buffer 88 13 70 17>      

选填的 byteOffset 和 length 参数指定一个将由 Buffer 共享的 arrayBuffer 中的内存范围。

const ab = new ArrayBuffer(10);     const buf = Buffer.from(ab, 0, 2);     console.log(buf.length);     // Prints: 2      

如果 arrayBuffer 不是一个有效的 ArrayBuffer 则抛出一个 TypeError 错误。