From dc1560866197a3c99c7035ac2cb521c0f22e396c Mon Sep 17 00:00:00 2001 From: James M Snell Date: Mon, 4 Jan 2021 11:39:09 -0800 Subject: [PATCH] doc: clarify Buffer.from when using ArrayBuffer Fixes: https://github.com/nodejs/node/issues/31348 Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/36785 Reviewed-By: Luigi Pinca Reviewed-By: Antoine du Hamel --- doc/api/buffer.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index d2beb06f593d46..c272a63ea53cf2 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -599,7 +599,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); @@ -635,6 +635,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: +``` + ### Static method: `Buffer.from(buffer)`