Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: clarify Buffer.from when using ArrayBuffer #36785

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 16 additions & 1 deletion doc/api/buffer.md
Expand Up @@ -612,7 +612,7 @@ added: v5.10.0
This creates a view of the [`ArrayBuffer`][] without copying the underlying
memory. For example, when passed a reference to the `.buffer` property of a
[`TypedArray`][] instance, the newly created `Buffer` will share the same
allocated memory as the [`TypedArray`][].
allocated memory as the [`TypedArray`][]'s underlying `ArrayBuffer`.

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

It is important to remember that a backing `ArrayBuffer` can cover a range
of memory that extends beyond the bounds of a `TypedArray` view. A new
`Buffer` created using the `buffer` property of a `TypedArray` may extend
beyond the range of the `TypedArray`:

```js
const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
console.log(arrA.buffer === arrB.buffer); // true

const buf = Buffer.from(arrB.buffer);
console.log(buf);
// Prints: <Buffer 63 64 65 66>
```

### Static method: `Buffer.from(buffer)`
<!-- YAML
added: v5.10.0
Expand Down