Skip to content

Commit 53b587a

Browse files
AndreasMadsentargos
authored andcommitted
doc: add documentation for buffer.byteOffset
Also document a common issue when casting a Buffer object to a TypedArray object. Fixes: #19301 PR-URL: #21718 Reviewed-By: Vse Mozhet Byt <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]>
1 parent 8c97ffb commit 53b587a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

doc/api/buffer.md

+25
Original file line numberDiff line numberDiff line change
@@ -992,6 +992,31 @@ console.log(buffer.buffer === arrayBuffer);
992992
// Prints: true
993993
```
994994

995+
### buf.byteOffset
996+
997+
* {integer} The `byteOffset` on the underlying `ArrayBuffer` object based on
998+
which this `Buffer` object is created.
999+
1000+
When setting `byteOffset` in `Buffer.from(ArrayBuffer, byteOffset, length)`
1001+
or sometimes when allocating a buffer smaller than `Buffer.poolSize` the
1002+
buffer doesn't start from a zero offset on the underlying `ArrayBuffer`.
1003+
1004+
This can cause problems when accessing the underlying `ArrayBuffer` directly
1005+
using `buf.buffer`, as the first bytes in this `ArrayBuffer` may be unrelated
1006+
to the `buf` object itself.
1007+
1008+
A common issue is when casting a `Buffer` object to a `TypedArray` object,
1009+
in this case one needs to specify the `byteOffset` correctly:
1010+
1011+
```js
1012+
// Create a buffer smaller than `Buffer.poolSize`.
1013+
const nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1014+
1015+
// When casting the Node.js Buffer to an Int8 TypedArray remember to use the
1016+
// byteOffset.
1017+
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
1018+
```
1019+
9951020
### buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])
9961021
<!-- YAML
9971022
added: v0.11.13

0 commit comments

Comments
 (0)