From 2c19f596adc758867121f6def24ec233e560cd33 Mon Sep 17 00:00:00 2001 From: Bryan English Date: Fri, 2 Jun 2023 17:44:47 -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 PR-URL: https://github.com/nodejs/node/pull/48274 Reviewed-By: Rich Trott Reviewed-By: LiviaMedeiros Reviewed-By: Luigi Pinca Reviewed-By: Mestery Reviewed-By: Harshitha K P --- doc/api/buffer.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 4ef77573adfe67..2dc36d902695cc 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -1116,6 +1116,12 @@ const { Buffer } = require('node:buffer'); const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); ``` +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 an +`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use +[`Buffer.copyBytesFrom()`][]. + A `TypeError` will be thrown if `array` is not an `Array` or another type appropriate for `Buffer.from()` variants. @@ -5488,6 +5494,7 @@ introducing security vulnerabilities into an application. [`Buffer.allocUnsafe()`]: #static-method-bufferallocunsafesize [`Buffer.allocUnsafeSlow()`]: #static-method-bufferallocunsafeslowsize [`Buffer.concat()`]: #static-method-bufferconcatlist-totallength +[`Buffer.copyBytesFrom()`]: #static-method-buffercopybytesfromview-offset-length [`Buffer.from(array)`]: #static-method-bufferfromarray [`Buffer.from(arrayBuf)`]: #static-method-bufferfromarraybuffer-byteoffset-length [`Buffer.from(buffer)`]: #static-method-bufferfrombuffer