Skip to content

Commit

Permalink
doc: clarify array args to Buffer.from()
Browse files Browse the repository at this point in the history
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: #28725
PR-URL: #48274
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: LiviaMedeiros <livia@cirno.name>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Mestery <mestery@protonmail.com>
Reviewed-By: Harshitha K P <harshitha014@gmail.com>
  • Loading branch information
bengl authored and danielleadams committed Jul 6, 2023
1 parent 8648373 commit eb03f41
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions doc/api/buffer.md
Original file line number Diff line number Diff line change
Expand Up @@ -1114,6 +1114,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.

Expand Down Expand Up @@ -5470,6 +5476,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
Expand Down

0 comments on commit eb03f41

Please sign in to comment.