Skip to content

Commit dc15608

Browse files
jasnelltargos
authored andcommitted
doc: clarify Buffer.from when using ArrayBuffer
Fixes: #31348 Signed-off-by: James M Snell <jasnell@gmail.com> PR-URL: #36785 Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 67a6e9c commit dc15608

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

doc/api/buffer.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,7 @@ added: v5.10.0
599599
This creates a view of the [`ArrayBuffer`][] without copying the underlying
600600
memory. For example, when passed a reference to the `.buffer` property of a
601601
[`TypedArray`][] instance, the newly created `Buffer` will share the same
602-
allocated memory as the [`TypedArray`][].
602+
allocated memory as the [`TypedArray`][]'s underlying `ArrayBuffer`.
603603

604604
```js
605605
const arr = new Uint16Array(2);
@@ -635,6 +635,21 @@ A `TypeError` will be thrown if `arrayBuffer` is not an [`ArrayBuffer`][] or a
635635
[`SharedArrayBuffer`][] or another type appropriate for `Buffer.from()`
636636
variants.
637637

638+
It is important to remember that a backing `ArrayBuffer` can cover a range
639+
of memory that extends beyond the bounds of a `TypedArray` view. A new
640+
`Buffer` created using the `buffer` property of a `TypedArray` may extend
641+
beyond the range of the `TypedArray`:
642+
643+
```js
644+
const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
645+
const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
646+
console.log(arrA.buffer === arrB.buffer); // true
647+
648+
const buf = Buffer.from(arrB.buffer);
649+
console.log(buf);
650+
// Prints: <Buffer 63 64 65 66>
651+
```
652+
638653
### Static method: `Buffer.from(buffer)`
639654
<!-- YAML
640655
added: v5.10.0

0 commit comments

Comments
 (0)