From 45707aee7c307bbaef27f26893628325eb0d1f20 Mon Sep 17 00:00:00 2001 From: Bryan English Date: Wed, 31 May 2023 17:30:36 -0400 Subject: [PATCH] doc: clarify array args to Buffer.from() The code for Buffer.from() treats non-Buffer and non-Uint8Array Array-likes as Arrays. This creates some confusion when passing various TypedArrays to Buffer.from(). The documentation now reflects the actual behavior. Fixes: https://github.com/nodejs/node/issues/28725 --- doc/api/buffer.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 981ef7aa2d4071..02580dcfe0a17a 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -1118,6 +1118,12 @@ const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); ``` +Note that if `array` is an `Array`-like object (that is, one with a `length` +property of type `number`) it is treated as if it is an array, unless it is a +`Buffer` or a `Uint8Array`. This means all other `TypedArray` variants get +treated as `Array`. To create a `Buffer` from the underlying `ArrayBuffer`, use +the `.buffer` property directly. + A `TypeError` will be thrown if `array` is not an `Array` or another type appropriate for `Buffer.from()` variants.