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 錯誤。