buf.byteOffset
- <integer>
Buffer
底层ArrayBuffer
对象的byteOffset
。
当在 Buffer.from(ArrayBuffer, byteOffset, length)
中设置 byteOffset
时,或者有时在分配小于 Buffer.poolSize
的 Buffer
时,缓冲区不会从底层 ArrayBuffer
上的零偏移量开始。
这在使用 buf.buffer
直接访问底层 ArrayBuffer
时可能会导致问题,因为 ArrayBuffer
的其他部分可能与 Buffer
对象本身无关。
创建与 Buffer
共享内存的 TypedArray
对象时的常见问题是,在这种情况下,需要正确指定 byteOffset
:
import { Buffer } from 'node:buffer';
// 创建小于 `Buffer.poolSize` 的缓冲区。
const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// 当将 Node.js 缓冲区转换为 Int8Array 时,
// 使用 byteOffset 仅引用包含 `nodeBuffer` 内存的 `nodeBuffer.buffer` 部分。
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
const { Buffer } = require('node:buffer');
// 创建小于 `Buffer.poolSize` 的缓冲区。
const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// 当将 Node.js 缓冲区转换为 Int8Array 时,
// 使用 byteOffset 仅引用包含 `nodeBuffer` 内存的 `nodeBuffer.buffer` 部分。
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
- <integer> The
byteOffset
of theBuffer
s underlyingArrayBuffer
object.
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
.
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.
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);