buf.byteOffset


  • <integer> Buffer 所依赖的 ArrayBuffer 对象的 byteOffset

Buffer.from(ArrayBuffer, byteOffset, length) 中设置 byteOffset 时,或者有时在分配比 Buffer.poolSize 小的 Buffer 时,缓冲区并不是从底层 ArrayBuffer 的零偏移量开始的。

【When setting byteOffset in Buffer.from(ArrayBuffer, byteOffset, length), or sometimes when allocating a Buffer smaller than Buffer.poolSize, the buffer does not start from a zero offset on the underlying ArrayBuffer.】

在使用 buf.buffer 直接访问底层 ArrayBuffer 时,这可能会引发问题,因为 ArrayBuffer 的其他部分可能与 Buffer 对象本身无关。

【This can cause problems when accessing the underlying ArrayBuffer directly using buf.buffer, as other parts of the ArrayBuffer may be unrelated to the Buffer object itself.】

在创建与 Buffer 共享内存的 TypedArray 对象时,一个常见的问题是需要正确指定 byteOffset

【A common issue when creating a TypedArray object that shares its memory with a Buffer is that in this case one needs to specify the byteOffset correctly:】

import { Buffer } from 'node:buffer';

// Create a buffer smaller than `Buffer.poolSize`.
const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

// When casting the Node.js Buffer to an Int8Array, use the byteOffset
// to refer only to the part of `nodeBuffer.buffer` that contains the memory
// for `nodeBuffer`.
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);const { Buffer } = require('node:buffer');

// Create a buffer smaller than `Buffer.poolSize`.
const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

// When casting the Node.js Buffer to an Int8Array, use the byteOffset
// to refer only to the part of `nodeBuffer.buffer` that contains the memory
// for `nodeBuffer`.
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);