Skip to content

Commit 5bc5161

Browse files
addaleaxMylesBorins
authored andcommittedMar 11, 2020
doc: improve Buffer documentation
Various improvements to the Buffer docs. PR-URL: #32086 Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 35bea07 commit 5bc5161

File tree

1 file changed

+534
-586
lines changed

1 file changed

+534
-586
lines changed
 

‎doc/api/buffer.md

+534-586
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,20 @@
44

55
> Stability: 2 - Stable
66
7-
Prior to the introduction of [`TypedArray`][], the JavaScript language had no
8-
mechanism for reading or manipulating streams of binary data. The `Buffer` class
9-
was introduced as part of the Node.js API to enable interaction with octet
10-
streams in TCP streams, file system operations, and other contexts.
7+
In Node.js, `Buffer` objects are used to represent binary data in the form
8+
of a sequence of bytes. Many Node.js APIs, for example streams and file system
9+
operations, support `Buffer`s, as interactions with the operating system or
10+
other processes generally always happen in terms of binary data.
1111

12-
With [`TypedArray`][] now available, the `Buffer` class implements the
13-
[`Uint8Array`][] API in a manner that is more optimized and suitable for
14-
Node.js.
12+
The `Buffer` class is a subclass of the [`Uint8Array`][] class that is built
13+
into the JavaScript language. A number of additional methods are supported
14+
that cover additional use cases. Node.js APIs accept plain [`Uint8Array`][]s
15+
wherever `Buffer`s are supported as well.
1516

16-
Instances of the `Buffer` class are similar to arrays of integers from `0` to
17-
`255` (other integers are coerced to this range by `& 255` operation) but
18-
correspond to fixed-sized, raw memory allocations outside the V8 heap.
19-
The size of the `Buffer` is established when it is created and cannot be
20-
changed.
17+
Instances of the `Buffer` class, and [`Uint8Array`][]s in general,
18+
are similar to arrays of integers from `0` to `255`, but correspond to
19+
fixed-sized blocks of memory and cannot contain any other values.
20+
The size of a `Buffer` is established when it is created and cannot be changed.
2121

2222
The `Buffer` class is within the global scope, making it unlikely that one
2323
would need to ever use `require('buffer').Buffer`.
@@ -26,129 +26,33 @@ would need to ever use `require('buffer').Buffer`.
2626
// Creates a zero-filled Buffer of length 10.
2727
const buf1 = Buffer.alloc(10);
2828

29-
// Creates a Buffer of length 10, filled with 0x1.
29+
// Creates a Buffer of length 10,
30+
// filled with bytes which all have the value `1`.
3031
const buf2 = Buffer.alloc(10, 1);
3132

3233
// Creates an uninitialized buffer of length 10.
3334
// This is faster than calling Buffer.alloc() but the returned
3435
// Buffer instance might contain old data that needs to be
35-
// overwritten using either fill() or write().
36+
// overwritten using fill(), write(), or other functions that fill the Buffer's
37+
// contents.
3638
const buf3 = Buffer.allocUnsafe(10);
3739

38-
// Creates a Buffer containing [0x1, 0x2, 0x3].
40+
// Creates a Buffer containing the bytes [1, 2, 3].
3941
const buf4 = Buffer.from([1, 2, 3]);
4042

41-
// Creates a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74].
42-
const buf5 = Buffer.from('tést');
43+
// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
44+
// are all truncated using `(value & 255)` to fit into the range 0–255.
45+
const buf5 = Buffer.from([257, 257.5, -255, '1']);
4346

44-
// Creates a Buffer containing Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
45-
const buf6 = Buffer.from('tést', 'latin1');
46-
```
47-
48-
## `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`
49-
50-
In versions of Node.js prior to 6.0.0, `Buffer` instances were created using the
51-
`Buffer` constructor function, which allocates the returned `Buffer`
52-
differently based on what arguments are provided:
53-
54-
* Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`)
55-
allocates a new `Buffer` object of the specified size. Prior to Node.js 8.0.0,
56-
the memory allocated for such `Buffer` instances is *not* initialized and
57-
*can contain sensitive data*. Such `Buffer` instances *must* be subsequently
58-
initialized by using either [`buf.fill(0)`][`buf.fill()`] or by writing to the
59-
entire `Buffer`. While this behavior is *intentional* to improve performance,
60-
development experience has demonstrated that a more explicit distinction is
61-
required between creating a fast-but-uninitialized `Buffer` versus creating a
62-
slower-but-safer `Buffer`. Since Node.js 8.0.0, `Buffer(num)` and `new
63-
Buffer(num)` return a `Buffer` with initialized memory.
64-
* Passing a string, array, or `Buffer` as the first argument copies the
65-
passed object's data into the `Buffer`.
66-
* Passing an [`ArrayBuffer`][] or a [`SharedArrayBuffer`][] returns a `Buffer`
67-
that shares allocated memory with the given array buffer.
68-
69-
Because the behavior of `new Buffer()` is different depending on the type of the
70-
first argument, security and reliability issues can be inadvertently introduced
71-
into applications when argument validation or `Buffer` initialization is not
72-
performed.
73-
74-
For example, if an attacker can cause an application to receive a number where
75-
a string is expected, the application may call `new Buffer(100)`
76-
instead of `new Buffer("100")`, it will allocate a 100 byte buffer instead
77-
of allocating a 3 byte buffer with content `"100"`. This is commonly possible
78-
using JSON API calls. Since JSON distinguishes between numeric and string types,
79-
it allows injection of numbers where a naive application might expect to always
80-
receive a string. Before Node.js 8.0.0, the 100 byte buffer might contain
81-
arbitrary pre-existing in-memory data, so may be used to expose in-memory
82-
secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot
83-
occur because the data is zero-filled. However, other attacks are still
84-
possible, such as causing very large buffers to be allocated by the server,
85-
leading to performance degradation or crashing on memory exhaustion.
86-
87-
To make the creation of `Buffer` instances more reliable and less error-prone,
88-
the various forms of the `new Buffer()` constructor have been **deprecated**
89-
and replaced by separate `Buffer.from()`, [`Buffer.alloc()`][], and
90-
[`Buffer.allocUnsafe()`][] methods.
91-
92-
*Developers should migrate all existing uses of the `new Buffer()` constructors
93-
to one of these new APIs.*
94-
95-
* [`Buffer.from(array)`][] returns a new `Buffer` that *contains a copy* of the
96-
provided octets.
97-
* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
98-
returns a new `Buffer` that *shares the same allocated memory* as the given
99-
[`ArrayBuffer`][].
100-
* [`Buffer.from(buffer)`][] returns a new `Buffer` that *contains a copy* of the
101-
contents of the given `Buffer`.
102-
* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new
103-
`Buffer` that *contains a copy* of the provided string.
104-
* [`Buffer.alloc(size[, fill[, encoding]])`][`Buffer.alloc()`] returns a new
105-
initialized `Buffer` of the specified size. This method is slower than
106-
[`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] but guarantees that newly
107-
created `Buffer` instances never contain old data that is potentially
108-
sensitive. A `TypeError` will be thrown if `size` is not a number.
109-
* [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] and
110-
[`Buffer.allocUnsafeSlow(size)`][`Buffer.allocUnsafeSlow()`] each return a
111-
new uninitialized `Buffer` of the specified `size`. Because the `Buffer` is
112-
uninitialized, the allocated segment of memory might contain old data that is
113-
potentially sensitive.
47+
// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
48+
// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
49+
// [116, 195, 169, 115, 116] (in decimal notation)
50+
const buf6 = Buffer.from('tést');
11451

115-
`Buffer` instances returned by [`Buffer.allocUnsafe()`][] *may* be allocated off
116-
a shared internal memory pool if `size` is less than or equal to half
117-
[`Buffer.poolSize`][]. Instances returned by [`Buffer.allocUnsafeSlow()`][]
118-
*never* use the shared internal memory pool.
119-
120-
### The `--zero-fill-buffers` command line option
121-
<!-- YAML
122-
added: v5.10.0
123-
-->
124-
125-
Node.js can be started using the `--zero-fill-buffers` command line option to
126-
cause all newly-allocated `Buffer` instances to be zero-filled upon creation by
127-
default. Without the option, buffers created with [`Buffer.allocUnsafe()`][],
128-
[`Buffer.allocUnsafeSlow()`][], and `new SlowBuffer(size)` are not zero-filled.
129-
Use of this flag can have a significant negative impact on performance. Use the
130-
`--zero-fill-buffers` option only when necessary to enforce that newly allocated
131-
`Buffer` instances cannot contain old data that is potentially sensitive.
132-
133-
```console
134-
$ node --zero-fill-buffers
135-
> Buffer.allocUnsafe(5);
136-
<Buffer 00 00 00 00 00>
52+
// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
53+
const buf7 = Buffer.from('tést', 'latin1');
13754
```
13855

139-
### What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` "unsafe"?
140-
141-
When calling [`Buffer.allocUnsafe()`][] and [`Buffer.allocUnsafeSlow()`][], the
142-
segment of allocated memory is *uninitialized* (it is not zeroed-out). While
143-
this design makes the allocation of memory quite fast, the allocated segment of
144-
memory might contain old data that is potentially sensitive. Using a `Buffer`
145-
created by [`Buffer.allocUnsafe()`][] without *completely* overwriting the
146-
memory can allow this old data to be leaked when the `Buffer` memory is read.
147-
148-
While there are clear performance advantages to using
149-
[`Buffer.allocUnsafe()`][], extra care *must* be taken in order to avoid
150-
introducing security vulnerabilities into an application.
151-
15256
## Buffers and Character Encodings
15357
<!-- YAML
15458
changes:
@@ -160,48 +64,76 @@ changes:
16064
description: Removed the deprecated `raw` and `raws` encodings.
16165
-->
16266

163-
When string data is stored in or extracted out of a `Buffer` instance, a
164-
character encoding may be specified.
67+
When converting between `Buffer`s and strings, a character encoding may be
68+
specified. If no character encoding is specified, UTF-8 will be used as the
69+
default.
16570

16671
```js
167-
const buf = Buffer.from('hello world', 'ascii');
72+
const buf = Buffer.from('hello world', 'utf8');
16873

16974
console.log(buf.toString('hex'));
17075
// Prints: 68656c6c6f20776f726c64
17176
console.log(buf.toString('base64'));
17277
// Prints: aGVsbG8gd29ybGQ=
17378

174-
console.log(Buffer.from('fhqwhgads', 'ascii'));
79+
console.log(Buffer.from('fhqwhgads', 'utf8'));
17580
// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
17681
console.log(Buffer.from('fhqwhgads', 'utf16le'));
17782
// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>
17883
```
17984

180-
The character encodings currently supported by Node.js include:
85+
The character encodings currently supported by Node.js are the following:
18186

182-
* `'ascii'`: For 7-bit ASCII data only. This encoding is fast and will strip
183-
the high bit if set.
87+
* `'utf8'`: Multi-byte encoded Unicode characters. Many web pages and other
88+
document formats use [UTF-8][]. This is the default character encoding.
89+
When decoding a `Buffer` into a string that does not exclusively contain
90+
valid UTF-8 data, the Unicode replacement character `U+FFFD` � will be used
91+
to represent those errors.
18492

185-
* `'utf8'`: Multibyte encoded Unicode characters. Many web pages and other
186-
document formats use UTF-8.
93+
* `'utf16le'`: Multi-byte encoded Unicode characters. Unlike `'utf8'`, each
94+
character in the string will be encoded using either 2 or 4 bytes.
95+
Node.js only supports the [little-endian][endianness] variant of [UTF-16][].
18796

188-
* `'utf16le'`: 2 or 4 bytes, little-endian encoded Unicode characters.
189-
Surrogate pairs (U+10000 to U+10FFFF) are supported.
97+
* `'latin1'`: Latin-1 stands for [ISO-8859-1][]. This character encoding only
98+
supports the Unicode characters from `U+0000` to `U+00FF`. Each character is
99+
encoded using a single byte. Characters that do not fit into that range are
100+
truncated and will be mapped to characters in that range.
190101

191-
* `'ucs2'`: Alias of `'utf16le'`.
102+
Converting a `Buffer` into a string using one of the above is referred to as
103+
decoding, and converting a string into a `Buffer` is referred to as encoding.
192104

193-
* `'base64'`: Base64 encoding. When creating a `Buffer` from a string,
105+
Node.js also supports the following two binary-to-text encodings. For
106+
binary-to-text encodings, the naming convention is reversed: Converting a
107+
`Buffer` into a string is typically referred to as encoding, and converting a
108+
string into a `Buffer` as decoding.
109+
110+
* `'base64'`: [Base64][] encoding. When creating a `Buffer` from a string,
194111
this encoding will also correctly accept "URL and Filename Safe Alphabet" as
195112
specified in [RFC 4648, Section 5][].
196113

197-
* `'latin1'`: A way of encoding the `Buffer` into a one-byte encoded string
198-
(as defined by the IANA in [RFC 1345][],
199-
page 63, to be the Latin-1 supplement block and C0/C1 control codes).
114+
* `'hex'`: Encode each byte as two hexadecimal characters. Data truncation
115+
may occur when decoding string that do exclusively contain valid hexadecimal
116+
characters. See below for an example.
117+
118+
The following legacy character encodings are also supported:
200119

201-
* `'binary'`: Alias for `'latin1'`.
120+
* `'ascii'`: For 7-bit [ASCII][] data only. When encoding a string into a
121+
`Buffer`, this is equivalent to using `'latin1'`. When decoding a `Buffer`
122+
into a string, using encoding this will additionally unset the highest bit of
123+
each byte before decoding as `'latin1'`.
124+
Generally, there should be no reason to use this encoding, as `'utf8'`
125+
(or, if the data is known to always be ASCII-only, `'latin1'`) will be a
126+
better choice when encoding or decoding ASCII-only text. It is only provided
127+
for legacy compatibility.
202128

203-
* `'hex'`: Encode each byte as two hexadecimal characters. Data truncation
204-
may occur for unsanitized input. For example:
129+
* `'binary'`: Alias for `'latin1'`. See [binary strings][] for more background
130+
on this topic. The name of this encoding can be very misleading, as all of the
131+
encodings listed here convert between strings and binary data. For converting
132+
between strings and `Buffer`s, typically `'utf-8'` is the right choice.
133+
134+
* `'ucs2'`: Alias of `'utf16le'`. UCS-2 used to refer to a variant of UTF-16
135+
that did not support characters that had code points larger than U+FFFF.
136+
In Node.js, these code points are always supported.
205137

206138
```js
207139
Buffer.from('1ag', 'hex');
@@ -222,34 +154,54 @@ the WHATWG specification it is possible that the server actually returned
222154
`'win-1252'`-encoded data, and using `'latin1'` encoding may incorrectly decode
223155
the characters.
224156

225-
## Buffers and TypedArray
157+
## Buffers and TypedArrays
226158
<!-- YAML
227159
changes:
228160
- version: v3.0.0
229161
pr-url: https://github.com/nodejs/node/pull/2002
230162
description: The `Buffer`s class now inherits from `Uint8Array`.
231163
-->
232164

233-
`Buffer` instances are also [`Uint8Array`][] instances. However, there are
234-
subtle incompatibilities with [`TypedArray`][]. For example, while
235-
[`ArrayBuffer#slice()`][] creates a copy of the slice, the implementation of
236-
[`Buffer#slice()`][`buf.slice()`] creates a view over the existing `Buffer`
237-
without copying, making [`Buffer#slice()`][`buf.slice()`] far more efficient.
165+
`Buffer` instances are also [`Uint8Array`][] instances, which is the language’s
166+
built-in class for working with binary data. [`Uint8Array`][] in turn is a
167+
subclass of [`TypedArray`][]. Therefore, all [`TypedArray`][] methods are also
168+
available on `Buffer`s. However, there are subtle incompatibilities between
169+
the `Buffer` API and the [`TypedArray`][] API.
170+
171+
In particular:
238172

239-
It is also possible to create new [`TypedArray`][] instances from a `Buffer`
240-
with the following caveats:
173+
* While [`TypedArray#slice()`][] creates a copy of part of the `TypedArray`,
174+
[`Buffer#slice()`][`buf.slice()`] creates a view over the existing `Buffer`
175+
without copying. This behavior can be surprising, and only exists for legacy
176+
compatibility. [`TypedArray#subarray()`][] can be used to achieve the behavior
177+
of [`Buffer#slice()`][`buf.slice()`] on both `Buffer`s and other
178+
`TypedArray`s.
179+
* [`buf.toString()`][] is incompatible with its `TypedArray` equivalent.
180+
* A number of methods, e.g. [`buf.indexOf()`][], support additional arguments.
241181

242-
1. The `Buffer` object's memory is copied to the [`TypedArray`][], not shared.
182+
There are two ways to create new [`TypedArray`][] instances from a `Buffer`.
243183

244-
2. The `Buffer` object's memory is interpreted as an array of distinct
245-
elements, and not as a byte array of the target type. That is,
184+
When passing a `Buffer` to a [`TypedArray`][] constructor, the `Buffer`’s
185+
elements will be copied, interpreted as an array of integers, and not as a byte
186+
array of the target type. For example,
246187
`new Uint32Array(Buffer.from([1, 2, 3, 4]))` creates a 4-element
247-
[`Uint32Array`][] with elements `[1, 2, 3, 4]`, not a [`Uint32Array`][] with a
248-
single element `[0x1020304]` or `[0x4030201]`.
188+
[`Uint32Array`][] with elements `[1, 2, 3, 4]`, rather than a
189+
[`Uint32Array`][] with a single element `[0x1020304]` or `[0x4030201]`.
249190

250-
It is possible to create a new `Buffer` that shares the same allocated memory as
251-
a [`TypedArray`][] instance by using the `TypedArray` object's `.buffer`
252-
property.
191+
In order to create a [`TypedArray`][] that shares its memory with the `Buffer`,
192+
the underlying [`ArrayBuffer`][] can be passed to the [`TypedArray`][]
193+
constructor instead:
194+
195+
```js
196+
const buf = Buffer.from('hello', 'utf16le');
197+
const uint16arr = new Uint16Array(
198+
buf.buffer, buf.byteOffset, buf.length / Uint16Array.BYTES_PER_ELEMENT);
199+
```
200+
201+
It is also possible to create a new `Buffer` that shares the same allocated
202+
memory as a [`TypedArray`][] instance by using the `TypedArray` object’s
203+
`.buffer` property in the same way. [`Buffer.from()`][`Buffer.from(arrayBuf)`]
204+
behaves like `new Uint8Array()` in this context.
253205

254206
```js
255207
const arr = new Uint16Array(2);
@@ -326,298 +278,101 @@ Additionally, the [`buf.values()`][], [`buf.keys()`][], and
326278
The `Buffer` class is a global type for dealing with binary data directly.
327279
It can be constructed in a variety of ways.
328280

329-
### `new Buffer(array)`
281+
### Class Method: `Buffer.alloc(size[, fill[, encoding]])`
330282
<!-- YAML
331-
deprecated: v6.0.0
283+
added: v5.10.0
332284
changes:
333285
- version: v10.0.0
334-
pr-url: https://github.com/nodejs/node/pull/19524
335-
description: Calling this constructor emits a deprecation warning when
336-
run from code outside the `node_modules` directory.
337-
- version: v7.2.1
338-
pr-url: https://github.com/nodejs/node/pull/9529
339-
description: Calling this constructor no longer emits a deprecation warning.
340-
- version: v7.0.0
341-
pr-url: https://github.com/nodejs/node/pull/8169
342-
description: Calling this constructor emits a deprecation warning now.
286+
pr-url: https://github.com/nodejs/node/pull/18129
287+
description: Attempting to fill a non-zero length buffer with a zero length
288+
buffer triggers a thrown exception.
289+
- version: v10.0.0
290+
pr-url: https://github.com/nodejs/node/pull/17427
291+
description: Specifying an invalid string for `fill` triggers a thrown
292+
exception.
293+
- version: v8.9.3
294+
pr-url: https://github.com/nodejs/node/pull/17428
295+
description: Specifying an invalid string for `fill` now results in a
296+
zero-filled buffer.
343297
-->
344298

345-
> Stability: 0 - Deprecated: Use [`Buffer.from(array)`][] instead.
346-
347-
* `array` {integer[]} An array of bytes to copy from.
299+
* `size` {integer} The desired length of the new `Buffer`.
300+
* `fill` {string|Buffer|Uint8Array|integer} A value to pre-fill the new `Buffer`
301+
with. **Default:** `0`.
302+
* `encoding` {string} If `fill` is a string, this is its encoding.
303+
**Default:** `'utf8'`.
348304

349-
Allocates a new `Buffer` using an `array` of octets.
305+
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
306+
`Buffer` will be zero-filled.
350307

351308
```js
352-
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
353-
const buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
309+
const buf = Buffer.alloc(5);
310+
311+
console.log(buf);
312+
// Prints: <Buffer 00 00 00 00 00>
354313
```
355314

356-
### `new Buffer(arrayBuffer[, byteOffset[, length]])`
357-
<!-- YAML
358-
added: v3.0.0
359-
deprecated: v6.0.0
360-
changes:
361-
- version: v10.0.0
362-
pr-url: https://github.com/nodejs/node/pull/19524
363-
description: Calling this constructor emits a deprecation warning when
364-
run from code outside the `node_modules` directory.
365-
- version: v7.2.1
366-
pr-url: https://github.com/nodejs/node/pull/9529
367-
description: Calling this constructor no longer emits a deprecation warning.
368-
- version: v7.0.0
369-
pr-url: https://github.com/nodejs/node/pull/8169
370-
description: Calling this constructor emits a deprecation warning now.
371-
- version: v6.0.0
372-
pr-url: https://github.com/nodejs/node/pull/4682
373-
description: The `byteOffset` and `length` parameters are supported now.
374-
-->
315+
If `size` is larger than
316+
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
317+
is thrown.
375318

376-
> Stability: 0 - Deprecated: Use
377-
> [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
378-
> instead.
319+
If `fill` is specified, the allocated `Buffer` will be initialized by calling
320+
[`buf.fill(fill)`][`buf.fill()`].
379321

380-
* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][],
381-
[`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][].
382-
* `byteOffset` {integer} Index of first byte to expose. **Default:** `0`.
383-
* `length` {integer} Number of bytes to expose.
384-
**Default:** `arrayBuffer.byteLength - byteOffset`.
322+
```js
323+
const buf = Buffer.alloc(5, 'a');
385324

386-
This creates a view of the [`ArrayBuffer`][] or [`SharedArrayBuffer`][] without
387-
copying the underlying memory. For example, when passed a reference to the
388-
`.buffer` property of a [`TypedArray`][] instance, the newly created `Buffer`
389-
will share the same allocated memory as the [`TypedArray`][].
325+
console.log(buf);
326+
// Prints: <Buffer 61 61 61 61 61>
327+
```
390328

391-
The optional `byteOffset` and `length` arguments specify a memory range within
392-
the `arrayBuffer` that will be shared by the `Buffer`.
329+
If both `fill` and `encoding` are specified, the allocated `Buffer` will be
330+
initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`].
393331

394332
```js
395-
const arr = new Uint16Array(2);
396-
397-
arr[0] = 5000;
398-
arr[1] = 4000;
399-
400-
// Shares memory with `arr`.
401-
const buf = new Buffer(arr.buffer);
333+
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
402334

403335
console.log(buf);
404-
// Prints: <Buffer 88 13 a0 0f>
336+
// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
337+
```
405338

406-
// Changing the original Uint16Array changes the Buffer also.
407-
arr[1] = 6000;
339+
Calling [`Buffer.alloc()`][] can be measurably slower than the alternative
340+
[`Buffer.allocUnsafe()`][] but ensures that the newly created `Buffer` instance
341+
contents will never contain sensitive data from previous allocations, including
342+
data that might not have been allocated for `Buffer`s.
408343

409-
console.log(buf);
410-
// Prints: <Buffer 88 13 70 17>
411-
```
344+
A `TypeError` will be thrown if `size` is not a number.
412345

413-
### `new Buffer(buffer)`
346+
### Class Method: `Buffer.allocUnsafe(size)`
414347
<!-- YAML
415-
deprecated: v6.0.0
348+
added: v5.10.0
416349
changes:
417-
- version: v10.0.0
418-
pr-url: https://github.com/nodejs/node/pull/19524
419-
description: Calling this constructor emits a deprecation warning when
420-
run from code outside the `node_modules` directory.
421-
- version: v7.2.1
422-
pr-url: https://github.com/nodejs/node/pull/9529
423-
description: Calling this constructor no longer emits a deprecation warning.
424350
- version: v7.0.0
425-
pr-url: https://github.com/nodejs/node/pull/8169
426-
description: Calling this constructor emits a deprecation warning now.
351+
pr-url: https://github.com/nodejs/node/pull/7079
352+
description: Passing a negative `size` will now throw an error.
427353
-->
428354

429-
> Stability: 0 - Deprecated: Use [`Buffer.from(buffer)`][] instead.
355+
* `size` {integer} The desired length of the new `Buffer`.
430356

431-
* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from
432-
which to copy data.
357+
Allocates a new `Buffer` of `size` bytes. If `size` is larger than
358+
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
359+
is thrown.
433360

434-
Copies the passed `buffer` data onto a new `Buffer` instance.
361+
The underlying memory for `Buffer` instances created in this way is *not
362+
initialized*. The contents of the newly created `Buffer` are unknown and
363+
*may contain sensitive data*. Use [`Buffer.alloc()`][] instead to initialize
364+
`Buffer` instances with zeroes.
435365

436366
```js
437-
const buf1 = new Buffer('buffer');
438-
const buf2 = new Buffer(buf1);
367+
const buf = Buffer.allocUnsafe(10);
439368

440-
buf1[0] = 0x61;
369+
console.log(buf);
370+
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
441371

442-
console.log(buf1.toString());
443-
// Prints: auffer
444-
console.log(buf2.toString());
445-
// Prints: buffer
446-
```
447-
448-
### `new Buffer(size)`
449-
<!-- YAML
450-
deprecated: v6.0.0
451-
changes:
452-
- version: v10.0.0
453-
pr-url: https://github.com/nodejs/node/pull/19524
454-
description: Calling this constructor emits a deprecation warning when
455-
run from code outside the `node_modules` directory.
456-
- version: v8.0.0
457-
pr-url: https://github.com/nodejs/node/pull/12141
458-
description: The `new Buffer(size)` will return zero-filled memory by
459-
default.
460-
- version: v7.2.1
461-
pr-url: https://github.com/nodejs/node/pull/9529
462-
description: Calling this constructor no longer emits a deprecation warning.
463-
- version: v7.0.0
464-
pr-url: https://github.com/nodejs/node/pull/8169
465-
description: Calling this constructor emits a deprecation warning now.
466-
-->
467-
468-
> Stability: 0 - Deprecated: Use [`Buffer.alloc()`][] instead (also see
469-
> [`Buffer.allocUnsafe()`][]).
470-
471-
* `size` {integer} The desired length of the new `Buffer`.
472-
473-
Allocates a new `Buffer` of `size` bytes. If `size` is larger than
474-
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
475-
is thrown. A zero-length `Buffer` is created if `size` is 0.
476-
477-
Prior to Node.js 8.0.0, the underlying memory for `Buffer` instances
478-
created in this way is *not initialized*. The contents of a newly created
479-
`Buffer` are unknown and *may contain sensitive data*. Use
480-
[`Buffer.alloc(size)`][`Buffer.alloc()`] instead to initialize a `Buffer`
481-
with zeroes.
482-
483-
```js
484-
const buf = new Buffer(10);
485-
486-
console.log(buf);
487-
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
488-
```
489-
490-
### `new Buffer(string[, encoding])`
491-
<!-- YAML
492-
deprecated: v6.0.0
493-
changes:
494-
- version: v10.0.0
495-
pr-url: https://github.com/nodejs/node/pull/19524
496-
description: Calling this constructor emits a deprecation warning when
497-
run from code outside the `node_modules` directory.
498-
- version: v7.2.1
499-
pr-url: https://github.com/nodejs/node/pull/9529
500-
description: Calling this constructor no longer emits a deprecation warning.
501-
- version: v7.0.0
502-
pr-url: https://github.com/nodejs/node/pull/8169
503-
description: Calling this constructor emits a deprecation warning now.
504-
-->
505-
506-
> Stability: 0 - Deprecated:
507-
> Use [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] instead.
508-
509-
* `string` {string} String to encode.
510-
* `encoding` {string} The encoding of `string`. **Default:** `'utf8'`.
511-
512-
Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
513-
the character encoding of `string`.
514-
515-
```js
516-
const buf1 = new Buffer('this is a tést');
517-
const buf2 = new Buffer('7468697320697320612074c3a97374', 'hex');
518-
519-
console.log(buf1.toString());
520-
// Prints: this is a tést
521-
console.log(buf2.toString());
522-
// Prints: this is a tést
523-
console.log(buf1.toString('ascii'));
524-
// Prints: this is a tC)st
525-
```
526-
527-
### Class Method: `Buffer.alloc(size[, fill[, encoding]])`
528-
<!-- YAML
529-
added: v5.10.0
530-
changes:
531-
- version: v10.0.0
532-
pr-url: https://github.com/nodejs/node/pull/18129
533-
description: Attempting to fill a non-zero length buffer with a zero length
534-
buffer triggers a thrown exception.
535-
- version: v10.0.0
536-
pr-url: https://github.com/nodejs/node/pull/17427
537-
description: Specifying an invalid string for `fill` triggers a thrown
538-
exception.
539-
- version: v8.9.3
540-
pr-url: https://github.com/nodejs/node/pull/17428
541-
description: Specifying an invalid string for `fill` now results in a
542-
zero-filled buffer.
543-
-->
544-
545-
* `size` {integer} The desired length of the new `Buffer`.
546-
* `fill` {string|Buffer|Uint8Array|integer} A value to pre-fill the new `Buffer`
547-
with. **Default:** `0`.
548-
* `encoding` {string} If `fill` is a string, this is its encoding.
549-
**Default:** `'utf8'`.
550-
551-
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
552-
`Buffer` will be *zero-filled*.
553-
554-
```js
555-
const buf = Buffer.alloc(5);
556-
557-
console.log(buf);
558-
// Prints: <Buffer 00 00 00 00 00>
559-
```
560-
561-
If `size` is larger than
562-
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
563-
is thrown. A zero-length `Buffer` is created if `size` is 0.
564-
565-
If `fill` is specified, the allocated `Buffer` will be initialized by calling
566-
[`buf.fill(fill)`][`buf.fill()`].
567-
568-
```js
569-
const buf = Buffer.alloc(5, 'a');
570-
571-
console.log(buf);
572-
// Prints: <Buffer 61 61 61 61 61>
573-
```
574-
575-
If both `fill` and `encoding` are specified, the allocated `Buffer` will be
576-
initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`].
577-
578-
```js
579-
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
580-
581-
console.log(buf);
582-
// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
583-
```
584-
585-
Calling [`Buffer.alloc()`][] can be significantly slower than the alternative
586-
[`Buffer.allocUnsafe()`][] but ensures that the newly created `Buffer` instance
587-
contents will *never contain sensitive data*.
588-
589-
A `TypeError` will be thrown if `size` is not a number.
590-
591-
### Class Method: `Buffer.allocUnsafe(size)`
592-
<!-- YAML
593-
added: v5.10.0
594-
changes:
595-
- version: v7.0.0
596-
pr-url: https://github.com/nodejs/node/pull/7079
597-
description: Passing a negative `size` will now throw an error.
598-
-->
599-
600-
* `size` {integer} The desired length of the new `Buffer`.
601-
602-
Allocates a new `Buffer` of `size` bytes. If `size` is larger than
603-
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
604-
is thrown. A zero-length `Buffer` is created if `size` is 0.
605-
606-
The underlying memory for `Buffer` instances created in this way is *not
607-
initialized*. The contents of the newly created `Buffer` are unknown and
608-
*may contain sensitive data*. Use [`Buffer.alloc()`][] instead to initialize
609-
`Buffer` instances with zeroes.
610-
611-
```js
612-
const buf = Buffer.allocUnsafe(10);
613-
614-
console.log(buf);
615-
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
616-
617-
buf.fill(0);
618-
619-
console.log(buf);
620-
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
372+
buf.fill(0);
373+
374+
console.log(buf);
375+
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
621376
```
622377

623378
A `TypeError` will be thrown if `size` is not a number.
@@ -657,7 +412,7 @@ allocations under 4KB are sliced from a single pre-allocated `Buffer`. This
657412
allows applications to avoid the garbage collection overhead of creating many
658413
individually allocated `Buffer` instances. This approach improves both
659414
performance and memory usage by eliminating the need to track and clean up as
660-
many persistent objects.
415+
many individual `ArrayBuffer` objects.
661416

662417
However, in the case where a developer may need to retain a small chunk of
663418
memory from a pool for an indeterminate amount of time, it may be appropriate
@@ -682,9 +437,6 @@ socket.on('readable', () => {
682437
});
683438
```
684439

685-
`Buffer.allocUnsafeSlow()` should be used only as a last resort after a
686-
developer has observed undue memory retention in their applications.
687-
688440
A `TypeError` will be thrown if `size` is not a number.
689441

690442
### Class Method: `Buffer.byteLength(string[, encoding])`
@@ -706,12 +458,12 @@ changes:
706458
**Default:** `'utf8'`.
707459
* Returns: {integer} The number of bytes contained within `string`.
708460

709-
Returns the actual byte length of a string. This is not the same as
710-
[`String.prototype.length`][] since that returns the number of *characters* in
711-
a string.
461+
Returns the byte length of a string when encoded using `encoding`.
462+
This is not the same as [`String.prototype.length`][], which does not account
463+
for the encoding that is used to convert the string into bytes.
712464

713465
For `'base64'` and `'hex'`, this function assumes valid input. For strings that
714-
contain non-Base64/Hex-encoded data (e.g. whitespace), the return value might be
466+
contain non-base64/hex-encoded data (e.g. whitespace), the return value might be
715467
greater than the length of a `Buffer` created from the string.
716468

717469
```js
@@ -723,7 +475,8 @@ console.log(`${str}: ${str.length} characters, ` +
723475
```
724476

725477
When `string` is a `Buffer`/[`DataView`][]/[`TypedArray`][]/[`ArrayBuffer`][]/
726-
[`SharedArrayBuffer`][], the actual byte length is returned.
478+
[`SharedArrayBuffer`][], the byte length as reported by `.byteLength`
479+
is returned.
727480

728481
### Class Method: `Buffer.compare(buf1, buf2)`
729482
<!-- YAML
@@ -736,9 +489,10 @@ changes:
736489

737490
* `buf1` {Buffer|Uint8Array}
738491
* `buf2` {Buffer|Uint8Array}
739-
* Returns: {integer}
492+
* Returns: {integer} Either `-1`, `0`, or `1`, depending on the result of the
493+
comparison. See [`buf.compare()`][] for details.
740494

741-
Compares `buf1` to `buf2` typically for the purpose of sorting arrays of
495+
Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of
742496
`Buffer` instances. This is equivalent to calling
743497
[`buf1.compare(buf2)`][`buf.compare()`].
744498

@@ -762,7 +516,7 @@ changes:
762516
-->
763517

764518
* `list` {Buffer[] | Uint8Array[]} List of `Buffer` or [`Uint8Array`][]
765-
instances to concat.
519+
instances to concatenate.
766520
* `totalLength` {integer} Total length of the `Buffer` instances in `list`
767521
when concatenated.
768522
* Returns: {Buffer}
@@ -774,9 +528,7 @@ If the list has no items, or if the `totalLength` is 0, then a new zero-length
774528
`Buffer` is returned.
775529

776530
If `totalLength` is not provided, it is calculated from the `Buffer` instances
777-
in `list`. This however causes an additional loop to be executed in order to
778-
calculate the `totalLength`, so it is faster to provide the length explicitly if
779-
it is already known.
531+
in `list` by adding their lengths.
780532

781533
If `totalLength` is provided, it is coerced to an unsigned integer. If the
782534
combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
@@ -808,10 +560,11 @@ added: v5.10.0
808560

809561
* `array` {integer[]}
810562

811-
Allocates a new `Buffer` using an `array` of octets.
563+
Allocates a new `Buffer` using an `array` of bytes in the range `0``255`.
564+
Array entries outside that range will be truncated to fit into it.
812565

813566
```js
814-
// Creates a new Buffer containing UTF-8 bytes of the string 'buffer'.
567+
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
815568
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
816569
```
817570

@@ -824,7 +577,8 @@ added: v5.10.0
824577
-->
825578

826579
* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][],
827-
[`SharedArrayBuffer`][], or the `.buffer` property of a [`TypedArray`][].
580+
[`SharedArrayBuffer`][], for example the `.buffer` property of a
581+
[`TypedArray`][].
828582
* `byteOffset` {integer} Index of first byte to expose. **Default:** `0`.
829583
* `length` {integer} Number of bytes to expose.
830584
**Default:** `arrayBuffer.byteLength - byteOffset`.
@@ -938,7 +692,7 @@ added: v5.10.0
938692
* `encoding` {string} The encoding of `string`. **Default:** `'utf8'`.
939693

940694
Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
941-
the character encoding of `string`.
695+
the character encoding to be used when converting `string` into bytes.
942696

943697
```js
944698
const buf1 = Buffer.from('this is a tést');
@@ -948,8 +702,8 @@ console.log(buf1.toString());
948702
// Prints: this is a tést
949703
console.log(buf2.toString());
950704
// Prints: this is a tést
951-
console.log(buf1.toString('ascii'));
952-
// Prints: this is a tC)st
705+
console.log(buf1.toString('latin1'));
706+
// Prints: this is a tést
953707
```
954708

955709
A `TypeError` will be thrown if `string` is not a string or other type
@@ -973,8 +727,8 @@ added: v0.9.1
973727
* `encoding` {string} A character encoding name to check.
974728
* Returns: {boolean}
975729

976-
Returns `true` if `encoding` contains a supported character encoding, or `false`
977-
otherwise.
730+
Returns `true` if `encoding` is the name of a supported character encoding,
731+
or `false` otherwise.
978732

979733
```js
980734
console.log(Buffer.isEncoding('utf-8'));
@@ -1013,11 +767,15 @@ The index operator `[index]` can be used to get and set the octet at position
1013767
range is between `0x00` and `0xFF` (hex) or `0` and `255` (decimal).
1014768

1015769
This operator is inherited from `Uint8Array`, so its behavior on out-of-bounds
1016-
access is the same as `UInt8Array`. In other words, getting returns `undefined`
1017-
and setting does nothing.
770+
access is the same as `Uint8Array`. In other words, `buf[index]` returns
771+
`undefined` when `index` is negative or `>= buf.length`, and
772+
`buf[index] = value` does not modify the buffer if `index` is negative or
773+
`>= buf.length`.
1018774

1019775
```js
1020776
// Copy an ASCII string into a `Buffer` one byte at a time.
777+
// (This only works for ASCII-only strings. In general, one should use
778+
// `Buffer.from()` to perform this conversion.)
1021779

1022780
const str = 'Node.js';
1023781
const buf = Buffer.allocUnsafe(str.length);
@@ -1026,7 +784,7 @@ for (let i = 0; i < str.length; i++) {
1026784
buf[i] = str.charCodeAt(i);
1027785
}
1028786

1029-
console.log(buf.toString('ascii'));
787+
console.log(buf.toString('utf8'));
1030788
// Prints: Node.js
1031789
```
1032790

@@ -1051,23 +809,24 @@ console.log(buffer.buffer === arrayBuffer);
1051809
* {integer} The `byteOffset` on the underlying `ArrayBuffer` object based on
1052810
which this `Buffer` object is created.
1053811

1054-
When setting `byteOffset` in `Buffer.from(ArrayBuffer, byteOffset, length)`
1055-
or sometimes when allocating a buffer smaller than `Buffer.poolSize` the
812+
When setting `byteOffset` in `Buffer.from(ArrayBuffer, byteOffset, length)`,
813+
or sometimes when allocating a buffer smaller than `Buffer.poolSize`, the
1056814
buffer doesn't start from a zero offset on the underlying `ArrayBuffer`.
1057815

1058816
This can cause problems when accessing the underlying `ArrayBuffer` directly
1059-
using `buf.buffer`, as the first bytes in this `ArrayBuffer` may be unrelated
817+
using `buf.buffer`, as other parts of the `ArrayBuffer` may be unrelated
1060818
to the `buf` object itself.
1061819

1062-
A common issue is when casting a `Buffer` object to a `TypedArray` object,
1063-
in this case one needs to specify the `byteOffset` correctly:
820+
A common issue when creating a `TypedArray` object that shares its memory with
821+
a `Buffer` is that in this case one needs to specify the `byteOffset` correctly:
1064822

1065823
```js
1066824
// Create a buffer smaller than `Buffer.poolSize`.
1067825
const nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1068826

1069-
// When casting the Node.js Buffer to an Int8 TypedArray remember to use the
1070-
// byteOffset.
827+
// When casting the Node.js Buffer to an Int8Array, use the byteOffset
828+
// to refer only to the part of `nodeBuffer.buffer` that contains the memory
829+
// for `nodeBuffer`.
1071830
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
1072831
```
1073832

@@ -1156,9 +915,13 @@ added: v0.1.90
1156915
inclusive). **Default:** [`buf.length`][].
1157916
* Returns: {integer} The number of bytes copied.
1158917

1159-
Copies data from a region of `buf` to a region in `target` even if the `target`
918+
Copies data from a region of `buf` to a region in `target`, even if the `target`
1160919
memory region overlaps with `buf`.
1161920

921+
[`TypedArray#set()`][] performs the same operation, and is available for all
922+
TypedArrays, including Node.js `Buffer`s, although it takes different
923+
function arguments.
924+
1162925
```js
1163926
// Create two `Buffer` instances.
1164927
const buf1 = Buffer.allocUnsafe(26);
@@ -1171,6 +934,8 @@ for (let i = 0; i < 26; i++) {
1171934

1172935
// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
1173936
buf1.copy(buf2, 8, 16, 20);
937+
// This is equivalent to:
938+
// buf2.set(buf1.subarray(16, 20), 8);
1174939

1175940
console.log(buf2.toString('ascii', 0, 25));
1176941
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
@@ -1234,7 +999,8 @@ changes:
1234999
* Returns: {boolean}
12351000

12361001
Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,
1237-
`false` otherwise.
1002+
`false` otherwise. Equivalent to
1003+
[`buf.compare(otherBuffer) === 0`][`buf.compare()`].
12381004

12391005
```js
12401006
const buf1 = Buffer.from('ABC');
@@ -1299,10 +1065,10 @@ If the final write of a `fill()` operation falls on a multi-byte character,
12991065
then only the bytes of that character that fit into `buf` are written:
13001066

13011067
```js
1302-
// Fill a `Buffer` with a two-byte character.
1068+
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
13031069

1304-
console.log(Buffer.allocUnsafe(3).fill('\u0222'));
1305-
// Prints: <Buffer c8 a2 c8>
1070+
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
1071+
// Prints: <Buffer c8 a2 c8 a2 c8>
13061072
```
13071073

13081074
If `value` contains invalid characters, it is truncated; if no valid
@@ -1543,42 +1309,22 @@ added: v0.1.90
15431309

15441310
* {integer}
15451311

1546-
Returns the amount of memory allocated for `buf` in bytes. This
1547-
does not necessarily reflect the amount of "usable" data within `buf`.
1312+
Returns the number of bytes in `buf`.
15481313

15491314
```js
1550-
// Create a `Buffer` and write a shorter ASCII string to it.
1315+
// Create a `Buffer` and write a shorter string to it using UTF-8.
15511316

15521317
const buf = Buffer.alloc(1234);
15531318

15541319
console.log(buf.length);
15551320
// Prints: 1234
15561321

1557-
buf.write('some string', 0, 'ascii');
1322+
buf.write('some string', 0, 'utf8');
15581323

15591324
console.log(buf.length);
15601325
// Prints: 1234
15611326
```
15621327

1563-
While the `length` property is not immutable, changing the value of `length`
1564-
can result in undefined and inconsistent behavior. Applications that wish to
1565-
modify the length of a `Buffer` should therefore treat `length` as read-only and
1566-
use [`buf.slice()`][] to create a new `Buffer`.
1567-
1568-
```js
1569-
let buf = Buffer.allocUnsafe(10);
1570-
1571-
buf.write('abcdefghj', 0, 'ascii');
1572-
1573-
console.log(buf.length);
1574-
// Prints: 10
1575-
1576-
buf = buf.slice(0, 5);
1577-
1578-
console.log(buf.length);
1579-
// Prints: 5
1580-
```
1581-
15821328
### `buf.parent`
15831329
<!-- YAML
15841330
deprecated: v8.0.0
@@ -1599,8 +1345,8 @@ added: v12.0.0
15991345
* Returns: {bigint}
16001346

16011347
Reads a signed 64-bit integer from `buf` at the specified `offset` with
1602-
the specified endian format (`readBigInt64BE()` returns big endian,
1603-
`readBigInt64LE()` returns little endian).
1348+
the specified [endianness][] (`readBigInt64BE()` reads as big endian,
1349+
`readBigInt64LE()` reads as little endian).
16041350

16051351
Integers read from a `Buffer` are interpreted as two's complement signed values.
16061352

@@ -1615,8 +1361,8 @@ added: v12.0.0
16151361
* Returns: {bigint}
16161362

16171363
Reads an unsigned 64-bit integer from `buf` at the specified `offset` with
1618-
specified endian format (`readBigUInt64BE()` returns big endian,
1619-
`readBigUInt64LE()` returns little endian).
1364+
the specified [endianness][] (`readBigUInt64BE()` reads as big endian,
1365+
`readBigUInt64LE()` reads as little endian).
16201366

16211367
```js
16221368
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
@@ -1643,8 +1389,8 @@ changes:
16431389
satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
16441390
* Returns: {number}
16451391

1646-
Reads a 64-bit double from `buf` at the specified `offset` with specified
1647-
endian format (`readDoubleBE()` returns big endian, `readDoubleLE()` returns
1392+
Reads a 64-bit double from `buf` at the specified `offset` with the specified
1393+
[endianness][] (`readDoubleBE()` reads as big endian, `readDoubleLE()` reads as
16481394
little endian).
16491395

16501396
```js
@@ -1673,8 +1419,8 @@ changes:
16731419
satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
16741420
* Returns: {number}
16751421

1676-
Reads a 32-bit float from `buf` at the specified `offset` with specified
1677-
endian format (`readFloatBE()` returns big endian, `readFloatLE()` returns
1422+
Reads a 32-bit float from `buf` at the specified `offset` with the specified
1423+
[endianness][] (`readFloatBE()` reads as big endian, `readFloatLE()` reads as
16781424
little endian).
16791425

16801426
```js
@@ -1733,8 +1479,8 @@ changes:
17331479
* Returns: {integer}
17341480

17351481
Reads a signed 16-bit integer from `buf` at the specified `offset` with
1736-
the specified endian format (`readInt16BE()` returns big endian,
1737-
`readInt16LE()` returns little endian).
1482+
the specified [endianness][] (`readInt16BE()` reads as big endian,
1483+
`readInt16LE()` reads as little endian).
17381484

17391485
Integers read from a `Buffer` are interpreted as two's complement signed values.
17401486

@@ -1765,8 +1511,8 @@ changes:
17651511
* Returns: {integer}
17661512

17671513
Reads a signed 32-bit integer from `buf` at the specified `offset` with
1768-
the specified endian format (`readInt32BE()` returns big endian,
1769-
`readInt32LE()` returns little endian).
1514+
the specified [endianness][] (`readInt32BE()` reads as big endian,
1515+
`readInt32LE()` reads as little endian).
17701516

17711517
Integers read from a `Buffer` are interpreted as two's complement signed values.
17721518

@@ -1858,8 +1604,8 @@ changes:
18581604
* Returns: {integer}
18591605

18601606
Reads an unsigned 16-bit integer from `buf` at the specified `offset` with
1861-
specified endian format (`readUInt16BE()` returns big endian, `readUInt16LE()`
1862-
returns little endian).
1607+
the specified [endianness][] (`readUInt16BE()` reads as big endian, `readUInt16LE()`
1608+
reads as little endian).
18631609

18641610
```js
18651611
const buf = Buffer.from([0x12, 0x34, 0x56]);
@@ -1892,8 +1638,8 @@ changes:
18921638
* Returns: {integer}
18931639

18941640
Reads an unsigned 32-bit integer from `buf` at the specified `offset` with
1895-
specified endian format (`readUInt32BE()` returns big endian,
1896-
`readUInt32LE()` returns little endian).
1641+
the specified [endianness][] (`readUInt32BE()` reads as big endian,
1642+
`readUInt32LE()` reads as little endian).
18971643

18981644
```js
18991645
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
@@ -1954,6 +1700,8 @@ offset and cropped by the `start` and `end` indices.
19541700
Specifying `end` greater than [`buf.length`][] will return the same result as
19551701
that of `end` equal to [`buf.length`][].
19561702

1703+
This method is inherited from [`TypedArray#subarray()`][].
1704+
19571705
Modifying the new `Buffer` slice will modify the memory in the original `Buffer`
19581706
because the allocated memory of the two objects overlap.
19591707

@@ -2129,9 +1877,6 @@ buf2.swap64();
21291877
// Throws ERR_INVALID_BUFFER_SIZE.
21301878
```
21311879

2132-
JavaScript cannot encode 64-bit integers. This method is intended
2133-
for working with 64-bit floats.
2134-
21351880
### `buf.toJSON()`
21361881
<!-- YAML
21371882
added: v0.9.2
@@ -2142,6 +1887,9 @@ added: v0.9.2
21421887
Returns a JSON representation of `buf`. [`JSON.stringify()`][] implicitly calls
21431888
this function when stringifying a `Buffer` instance.
21441889

1890+
`Buffer.from()` accepts objects in the format returned from this method.
1891+
In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`.
1892+
21451893
```js
21461894
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
21471895
const json = JSON.stringify(buf);
@@ -2151,7 +1899,7 @@ console.log(json);
21511899

21521900
const copy = JSON.parse(json, (key, value) => {
21531901
return value && value.type === 'Buffer' ?
2154-
Buffer.from(value.data) :
1902+
Buffer.from(value) :
21551903
value;
21561904
});
21571905

@@ -2172,8 +1920,9 @@ added: v0.1.90
21721920

21731921
Decodes `buf` to a string according to the specified character encoding in
21741922
`encoding`. `start` and `end` may be passed to decode only a subset of `buf`.
2175-
If a byte sequence in the input is not valid in the given `encoding` then
2176-
it is replaced with the replacement character `U+FFFD`.
1923+
1924+
If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8,
1925+
then each invalid byte is replaced with the replacement character `U+FFFD`.
21771926

21781927
The maximum length of a string instance (in UTF-16 code units) is available
21791928
as [`buffer.constants.MAX_STRING_LENGTH`][].
@@ -2186,9 +1935,9 @@ for (let i = 0; i < 26; i++) {
21861935
buf1[i] = i + 97;
21871936
}
21881937

2189-
console.log(buf1.toString('ascii'));
1938+
console.log(buf1.toString('utf8'));
21901939
// Prints: abcdefghijklmnopqrstuvwxyz
2191-
console.log(buf1.toString('ascii', 0, 5));
1940+
console.log(buf1.toString('utf8', 0, 5));
21921941
// Prints: abcde
21931942

21941943
const buf2 = Buffer.from('tést');
@@ -2245,7 +1994,7 @@ added: v0.1.90
22451994
* `string` {string} String to write to `buf`.
22461995
* `offset` {integer} Number of bytes to skip before starting to write `string`.
22471996
**Default:** `0`.
2248-
* `length` {integer} Number of bytes to write. **Default:**
1997+
* `length` {integer} Maximum number of bytes to write. **Default:**
22491998
`buf.length - offset`.
22501999
* `encoding` {string} The character encoding of `string`. **Default:** `'utf8'`.
22512000
* Returns: {integer} Number of bytes written.
@@ -2275,9 +2024,9 @@ added: v12.0.0
22752024
satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
22762025
* Returns: {integer} `offset` plus the number of bytes written.
22772026

2278-
Writes `value` to `buf` at the specified `offset` with specified endian
2279-
format (`writeBigInt64BE()` writes big endian, `writeBigInt64LE()` writes little
2280-
endian).
2027+
Writes `value` to `buf` at the specified `offset` with the specified
2028+
[endianness][] (`writeBigInt64BE()` writes as big endian, `writeBigInt64LE()`
2029+
writes as little endian).
22812030

22822031
`value` is interpreted and written as a two's complement signed integer.
22832032

@@ -2301,8 +2050,8 @@ added: v12.0.0
23012050
satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
23022051
* Returns: {integer} `offset` plus the number of bytes written.
23032052

2304-
Writes `value` to `buf` at the specified `offset` with specified endian
2305-
format (`writeBigUInt64BE()` writes big endian, `writeBigUInt64LE()` writes
2053+
Writes `value` to `buf` at the specified `offset` with specified [endianness][]
2054+
(`writeBigUInt64BE()` writes as big endian, `writeBigUInt64LE()` writes as
23062055
little endian).
23072056

23082057
```js
@@ -2330,10 +2079,10 @@ changes:
23302079
satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
23312080
* Returns: {integer} `offset` plus the number of bytes written.
23322081

2333-
Writes `value` to `buf` at the specified `offset` with specified endian
2334-
format (`writeDoubleBE()` writes big endian, `writeDoubleLE()` writes little
2335-
endian). `value` *should* be a valid 64-bit double. Behavior is undefined when
2336-
`value` is anything other than a 64-bit double.
2082+
Writes `value` to `buf` at the specified `offset` with the specified
2083+
[endianness][] (`writeDoubleBE()` writes as big endian, `writeDoubleLE()` writes
2084+
as little endian). `value` must be a JavaScript number. Behavior is undefined
2085+
when `value` is anything other than a JavaScript number.
23372086

23382087
```js
23392088
const buf = Buffer.allocUnsafe(8);
@@ -2365,10 +2114,10 @@ changes:
23652114
satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
23662115
* Returns: {integer} `offset` plus the number of bytes written.
23672116

2368-
Writes `value` to `buf` at the specified `offset` with specified endian
2369-
format (`writeFloatBE()` writes big endian, `writeFloatLE()` writes little
2370-
endian). `value` *should* be a valid 32-bit float. Behavior is undefined when
2371-
`value` is anything other than a 32-bit float.
2117+
Writes `value` to `buf` at the specified `offset` with specified [endianness][]
2118+
(`writeFloatBE()` writes as big endian, `writeFloatLE()` writes as little
2119+
endian). `value` must be a JavaScript number. Behavior is undefined when
2120+
`value` is anything other than a JavaScript number.
23722121

23732122
```js
23742123
const buf = Buffer.allocUnsafe(4);
@@ -2399,7 +2148,7 @@ changes:
23992148
satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
24002149
* Returns: {integer} `offset` plus the number of bytes written.
24012150

2402-
Writes `value` to `buf` at the specified `offset`. `value` *should* be a valid
2151+
Writes `value` to `buf` at the specified `offset`. `value` must be a valid
24032152
signed 8-bit integer. Behavior is undefined when `value` is anything other than
24042153
a signed 8-bit integer.
24052154

@@ -2431,9 +2180,9 @@ changes:
24312180
satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
24322181
* Returns: {integer} `offset` plus the number of bytes written.
24332182

2434-
Writes `value` to `buf` at the specified `offset` with specified endian
2435-
format (`writeInt16BE()` writes big endian, `writeInt16LE()` writes little
2436-
endian). `value` *should* be a valid signed 16-bit integer. Behavior is
2183+
Writes `value` to `buf` at the specified `offset` with the specified
2184+
[endianness][] (`writeInt16BE()` writes as big endian, `writeInt16LE()` writes
2185+
as little endian). `value` must be a valid signed 16-bit integer. Behavior is
24372186
undefined when `value` is anything other than a signed 16-bit integer.
24382187

24392188
`value` is interpreted and written as a two's complement signed integer.
@@ -2464,9 +2213,9 @@ changes:
24642213
satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
24652214
* Returns: {integer} `offset` plus the number of bytes written.
24662215

2467-
Writes `value` to `buf` at the specified `offset` with specified endian
2468-
format (`writeInt32BE()` writes big endian, `writeInt32LE()` writes little
2469-
endian). `value` *should* be a valid signed 32-bit integer. Behavior is
2216+
Writes `value` to `buf` at the specified `offset` with the specified
2217+
[endianness][] (`writeInt32BE()` writes aS big endian, `writeInt32LE()` writes
2218+
as little endian). `value` must be a valid signed 32-bit integer. Behavior is
24702219
undefined when `value` is anything other than a signed 32-bit integer.
24712220

24722221
`value` is interpreted and written as a two's complement signed integer.
@@ -2532,7 +2281,7 @@ changes:
25322281
satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
25332282
* Returns: {integer} `offset` plus the number of bytes written.
25342283

2535-
Writes `value` to `buf` at the specified `offset`. `value` *should* be a
2284+
Writes `value` to `buf` at the specified `offset`. `value` must be a
25362285
valid unsigned 8-bit integer. Behavior is undefined when `value` is anything
25372286
other than an unsigned 8-bit integer.
25382287

@@ -2564,9 +2313,9 @@ changes:
25642313
satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
25652314
* Returns: {integer} `offset` plus the number of bytes written.
25662315

2567-
Writes `value` to `buf` at the specified `offset` with specified endian
2568-
format (`writeUInt16BE()` writes big endian, `writeUInt16LE()` writes little
2569-
endian). `value` should be a valid unsigned 16-bit integer. Behavior is
2316+
Writes `value` to `buf` at the specified `offset` with the specified
2317+
[endianness][] (`writeUInt16BE()` writes as big endian, `writeUInt16LE()` writes
2318+
as little endian). `value` must be a valid unsigned 16-bit integer. Behavior is
25702319
undefined when `value` is anything other than an unsigned 16-bit integer.
25712320

25722321
```js
@@ -2601,9 +2350,9 @@ changes:
26012350
satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
26022351
* Returns: {integer} `offset` plus the number of bytes written.
26032352

2604-
Writes `value` to `buf` at the specified `offset` with specified endian
2605-
format (`writeUInt32BE()` writes big endian, `writeUInt32LE()` writes little
2606-
endian). `value` should be a valid unsigned 32-bit integer. Behavior is
2353+
Writes `value` to `buf` at the specified `offset` with the specified
2354+
[endianness][] (`writeUInt32BE()` writes as big endian, `writeUInt32LE()` writes
2355+
as little endian). `value` must be a valid unsigned 32-bit integer. Behavior is
26072356
undefined when `value` is anything other than an unsigned 32-bit integer.
26082357

26092358
```js
@@ -2656,6 +2405,138 @@ console.log(buf);
26562405
// Prints: <Buffer ab 90 78 56 34 12>
26572406
```
26582407

2408+
### `new Buffer(array)`
2409+
<!-- YAML
2410+
deprecated: v6.0.0
2411+
changes:
2412+
- version: v10.0.0
2413+
pr-url: https://github.com/nodejs/node/pull/19524
2414+
description: Calling this constructor emits a deprecation warning when
2415+
run from code outside the `node_modules` directory.
2416+
- version: v7.2.1
2417+
pr-url: https://github.com/nodejs/node/pull/9529
2418+
description: Calling this constructor no longer emits a deprecation warning.
2419+
- version: v7.0.0
2420+
pr-url: https://github.com/nodejs/node/pull/8169
2421+
description: Calling this constructor emits a deprecation warning now.
2422+
-->
2423+
2424+
> Stability: 0 - Deprecated: Use [`Buffer.from(array)`][] instead.
2425+
2426+
* `array` {integer[]} An array of bytes to copy from.
2427+
2428+
See [`Buffer.from(array)`][].
2429+
2430+
### `new Buffer(arrayBuffer[, byteOffset[, length]])`
2431+
<!-- YAML
2432+
added: v3.0.0
2433+
deprecated: v6.0.0
2434+
changes:
2435+
- version: v10.0.0
2436+
pr-url: https://github.com/nodejs/node/pull/19524
2437+
description: Calling this constructor emits a deprecation warning when
2438+
run from code outside the `node_modules` directory.
2439+
- version: v7.2.1
2440+
pr-url: https://github.com/nodejs/node/pull/9529
2441+
description: Calling this constructor no longer emits a deprecation warning.
2442+
- version: v7.0.0
2443+
pr-url: https://github.com/nodejs/node/pull/8169
2444+
description: Calling this constructor emits a deprecation warning now.
2445+
- version: v6.0.0
2446+
pr-url: https://github.com/nodejs/node/pull/4682
2447+
description: The `byteOffset` and `length` parameters are supported now.
2448+
-->
2449+
2450+
> Stability: 0 - Deprecated: Use
2451+
> [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
2452+
> instead.
2453+
2454+
* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][],
2455+
[`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][].
2456+
* `byteOffset` {integer} Index of first byte to expose. **Default:** `0`.
2457+
* `length` {integer} Number of bytes to expose.
2458+
**Default:** `arrayBuffer.byteLength - byteOffset`.
2459+
2460+
See
2461+
[`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`].
2462+
2463+
### `new Buffer(buffer)`
2464+
<!-- YAML
2465+
deprecated: v6.0.0
2466+
changes:
2467+
- version: v10.0.0
2468+
pr-url: https://github.com/nodejs/node/pull/19524
2469+
description: Calling this constructor emits a deprecation warning when
2470+
run from code outside the `node_modules` directory.
2471+
- version: v7.2.1
2472+
pr-url: https://github.com/nodejs/node/pull/9529
2473+
description: Calling this constructor no longer emits a deprecation warning.
2474+
- version: v7.0.0
2475+
pr-url: https://github.com/nodejs/node/pull/8169
2476+
description: Calling this constructor emits a deprecation warning now.
2477+
-->
2478+
2479+
> Stability: 0 - Deprecated: Use [`Buffer.from(buffer)`][] instead.
2480+
2481+
* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from
2482+
which to copy data.
2483+
2484+
See [`Buffer.from(buffer)`][].
2485+
2486+
### `new Buffer(size)`
2487+
<!-- YAML
2488+
deprecated: v6.0.0
2489+
changes:
2490+
- version: v10.0.0
2491+
pr-url: https://github.com/nodejs/node/pull/19524
2492+
description: Calling this constructor emits a deprecation warning when
2493+
run from code outside the `node_modules` directory.
2494+
- version: v8.0.0
2495+
pr-url: https://github.com/nodejs/node/pull/12141
2496+
description: The `new Buffer(size)` will return zero-filled memory by
2497+
default.
2498+
- version: v7.2.1
2499+
pr-url: https://github.com/nodejs/node/pull/9529
2500+
description: Calling this constructor no longer emits a deprecation warning.
2501+
- version: v7.0.0
2502+
pr-url: https://github.com/nodejs/node/pull/8169
2503+
description: Calling this constructor emits a deprecation warning now.
2504+
-->
2505+
2506+
> Stability: 0 - Deprecated: Use [`Buffer.alloc()`][] instead (also see
2507+
> [`Buffer.allocUnsafe()`][]).
2508+
2509+
* `size` {integer} The desired length of the new `Buffer`.
2510+
2511+
See [`Buffer.alloc()`][] and [`Buffer.allocUnsafe()`][]. This variant of the
2512+
constructor is equivalent to [`Buffer.allocUnsafe()`][], although using
2513+
[`Buffer.alloc()`][] is recommended in code paths that are not critical to
2514+
performance.
2515+
2516+
### `new Buffer(string[, encoding])`
2517+
<!-- YAML
2518+
deprecated: v6.0.0
2519+
changes:
2520+
- version: v10.0.0
2521+
pr-url: https://github.com/nodejs/node/pull/19524
2522+
description: Calling this constructor emits a deprecation warning when
2523+
run from code outside the `node_modules` directory.
2524+
- version: v7.2.1
2525+
pr-url: https://github.com/nodejs/node/pull/9529
2526+
description: Calling this constructor no longer emits a deprecation warning.
2527+
- version: v7.0.0
2528+
pr-url: https://github.com/nodejs/node/pull/8169
2529+
description: Calling this constructor emits a deprecation warning now.
2530+
-->
2531+
2532+
> Stability: 0 - Deprecated:
2533+
> Use [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] instead.
2534+
2535+
* `string` {string} String to encode.
2536+
* `encoding` {string} The encoding of `string`. **Default:** `'utf8'`.
2537+
2538+
See [`Buffer.from(string[, encoding])`][`Buffer.from(string)`].
2539+
26592540
## `buffer.INSPECT_MAX_BYTES`
26602541
<!-- YAML
26612542
added: v0.5.4
@@ -2729,36 +2610,9 @@ deprecated: v6.0.0
27292610

27302611
> Stability: 0 - Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.
27312612
2732-
Returns an un-pooled `Buffer`.
2733-
2734-
In order to avoid the garbage collection overhead of creating many individually
2735-
allocated `Buffer` instances, by default allocations under 4KB are sliced from a
2736-
single larger allocated object.
2737-
2738-
In the case where a developer may need to retain a small chunk of memory from a
2739-
pool for an indeterminate amount of time, it may be appropriate to create an
2740-
un-pooled `Buffer` instance using `SlowBuffer` then copy out the relevant bits.
2741-
2742-
```js
2743-
// Need to keep around a few small chunks of memory.
2744-
const store = [];
2745-
2746-
socket.on('readable', () => {
2747-
let data;
2748-
while (null !== (data = readable.read())) {
2749-
// Allocate for retained data.
2750-
const sb = SlowBuffer(10);
2751-
2752-
// Copy the data into the new allocation.
2753-
data.copy(sb, 0, 0, 10);
2754-
2755-
store.push(sb);
2756-
}
2757-
});
2758-
```
2759-
2760-
Use of `SlowBuffer` should be used only as a last resort *after* a developer
2761-
has observed undue memory retention in their applications.
2613+
See [`Buffer.allocUnsafeSlow()`][]. This was never a class in the sense that
2614+
the constructor always returned a `Buffer` instance, rather than a `SlowBuffer`
2615+
instance.
27622616

27632617
### `new SlowBuffer(size)`
27642618
<!-- YAML
@@ -2769,28 +2623,7 @@ deprecated: v6.0.0
27692623
27702624
* `size` {integer} The desired length of the new `SlowBuffer`.
27712625

2772-
Allocates a new `Buffer` of `size` bytes. If `size` is larger than
2773-
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
2774-
is thrown. A zero-length `Buffer` is created if `size` is 0.
2775-
2776-
The underlying memory for `SlowBuffer` instances is *not initialized*. The
2777-
contents of a newly created `SlowBuffer` are unknown and may contain sensitive
2778-
data. Use [`buf.fill(0)`][`buf.fill()`] to initialize a `SlowBuffer` with
2779-
zeroes.
2780-
2781-
```js
2782-
const { SlowBuffer } = require('buffer');
2783-
2784-
const buf = new SlowBuffer(5);
2785-
2786-
console.log(buf);
2787-
// Prints: (contents may vary): <Buffer 78 e0 82 02 01>
2788-
2789-
buf.fill(0);
2790-
2791-
console.log(buf);
2792-
// Prints: <Buffer 00 00 00 00 00>
2793-
```
2626+
See [`Buffer.allocUnsafeSlow()`][].
27942627

27952628
## Buffer Constants
27962629
<!-- YAML
@@ -2807,8 +2640,8 @@ added: v8.2.0
28072640

28082641
* {integer} The largest size allowed for a single `Buffer` instance.
28092642

2810-
On 32-bit architectures, this value is `(2^30)-1` (~1GB).
2811-
On 64-bit architectures, this value is `(2^31)-1` (~2GB).
2643+
On 32-bit architectures, this value currently is `(2^30)-1` (~1GB).
2644+
On 64-bit architectures, this value currently is `(2^31)-1` (~2GB).
28122645

28132646
This value is also available as [`buffer.kMaxLength`][].
28142647

@@ -2824,10 +2657,114 @@ in UTF-16 code units.
28242657

28252658
This value may depend on the JS engine that is being used.
28262659

2827-
[RFC 1345]: https://tools.ietf.org/html/rfc1345
2660+
## `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`
2661+
2662+
In versions of Node.js prior to 6.0.0, `Buffer` instances were created using the
2663+
`Buffer` constructor function, which allocates the returned `Buffer`
2664+
differently based on what arguments are provided:
2665+
2666+
* Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`)
2667+
allocates a new `Buffer` object of the specified size. Prior to Node.js 8.0.0,
2668+
the memory allocated for such `Buffer` instances is *not* initialized and
2669+
*can contain sensitive data*. Such `Buffer` instances *must* be subsequently
2670+
initialized by using either [`buf.fill(0)`][`buf.fill()`] or by writing to the
2671+
entire `Buffer` before reading data from the `Buffer`.
2672+
While this behavior is *intentional* to improve performance,
2673+
development experience has demonstrated that a more explicit distinction is
2674+
required between creating a fast-but-uninitialized `Buffer` versus creating a
2675+
slower-but-safer `Buffer`. Since Node.js 8.0.0, `Buffer(num)` and `new
2676+
Buffer(num)` return a `Buffer` with initialized memory.
2677+
* Passing a string, array, or `Buffer` as the first argument copies the
2678+
passed object's data into the `Buffer`.
2679+
* Passing an [`ArrayBuffer`][] or a [`SharedArrayBuffer`][] returns a `Buffer`
2680+
that shares allocated memory with the given array buffer.
2681+
2682+
Because the behavior of `new Buffer()` is different depending on the type of the
2683+
first argument, security and reliability issues can be inadvertently introduced
2684+
into applications when argument validation or `Buffer` initialization is not
2685+
performed.
2686+
2687+
For example, if an attacker can cause an application to receive a number where
2688+
a string is expected, the application may call `new Buffer(100)`
2689+
instead of `new Buffer("100")`, leading it to allocate a 100 byte buffer instead
2690+
of allocating a 3 byte buffer with content `"100"`. This is commonly possible
2691+
using JSON API calls. Since JSON distinguishes between numeric and string types,
2692+
it allows injection of numbers where a naively written application that does not
2693+
validate its input sufficiently might expect to always receive a string.
2694+
Before Node.js 8.0.0, the 100 byte buffer might contain
2695+
arbitrary pre-existing in-memory data, so may be used to expose in-memory
2696+
secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot
2697+
occur because the data is zero-filled. However, other attacks are still
2698+
possible, such as causing very large buffers to be allocated by the server,
2699+
leading to performance degradation or crashing on memory exhaustion.
2700+
2701+
To make the creation of `Buffer` instances more reliable and less error-prone,
2702+
the various forms of the `new Buffer()` constructor have been **deprecated**
2703+
and replaced by separate `Buffer.from()`, [`Buffer.alloc()`][], and
2704+
[`Buffer.allocUnsafe()`][] methods.
2705+
2706+
*Developers should migrate all existing uses of the `new Buffer()` constructors
2707+
to one of these new APIs.*
2708+
2709+
* [`Buffer.from(array)`][] returns a new `Buffer` that *contains a copy* of the
2710+
provided octets.
2711+
* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
2712+
returns a new `Buffer` that *shares the same allocated memory* as the given
2713+
[`ArrayBuffer`][].
2714+
* [`Buffer.from(buffer)`][] returns a new `Buffer` that *contains a copy* of the
2715+
contents of the given `Buffer`.
2716+
* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new
2717+
`Buffer` that *contains a copy* of the provided string.
2718+
* [`Buffer.alloc(size[, fill[, encoding]])`][`Buffer.alloc()`] returns a new
2719+
initialized `Buffer` of the specified size. This method is slower than
2720+
[`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] but guarantees that newly
2721+
created `Buffer` instances never contain old data that is potentially
2722+
sensitive. A `TypeError` will be thrown if `size` is not a number.
2723+
* [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] and
2724+
[`Buffer.allocUnsafeSlow(size)`][`Buffer.allocUnsafeSlow()`] each return a
2725+
new uninitialized `Buffer` of the specified `size`. Because the `Buffer` is
2726+
uninitialized, the allocated segment of memory might contain old data that is
2727+
potentially sensitive.
2728+
2729+
`Buffer` instances returned by [`Buffer.allocUnsafe()`][] *may* be allocated off
2730+
a shared internal memory pool if `size` is less than or equal to half
2731+
[`Buffer.poolSize`][]. Instances returned by [`Buffer.allocUnsafeSlow()`][]
2732+
*never* use the shared internal memory pool.
2733+
2734+
### The `--zero-fill-buffers` command line option
2735+
<!-- YAML
2736+
added: v5.10.0
2737+
-->
2738+
2739+
Node.js can be started using the `--zero-fill-buffers` command line option to
2740+
cause all newly-allocated `Buffer` instances to be zero-filled upon creation by
2741+
default. Without the option, buffers created with [`Buffer.allocUnsafe()`][],
2742+
[`Buffer.allocUnsafeSlow()`][], and `new SlowBuffer(size)` are not zero-filled.
2743+
Use of this flag can have a measurable negative impact on performance. Use the
2744+
`--zero-fill-buffers` option only when necessary to enforce that newly allocated
2745+
`Buffer` instances cannot contain old data that is potentially sensitive.
2746+
2747+
```console
2748+
$ node --zero-fill-buffers
2749+
> Buffer.allocUnsafe(5);
2750+
<Buffer 00 00 00 00 00>
2751+
```
2752+
2753+
### What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` "unsafe"?
2754+
2755+
When calling [`Buffer.allocUnsafe()`][] and [`Buffer.allocUnsafeSlow()`][], the
2756+
segment of allocated memory is *uninitialized* (it is not zeroed-out). While
2757+
this design makes the allocation of memory quite fast, the allocated segment of
2758+
memory might contain old data that is potentially sensitive. Using a `Buffer`
2759+
created by [`Buffer.allocUnsafe()`][] without *completely* overwriting the
2760+
memory can allow this old data to be leaked when the `Buffer` memory is read.
2761+
2762+
While there are clear performance advantages to using
2763+
[`Buffer.allocUnsafe()`][], extra care *must* be taken in order to avoid
2764+
introducing security vulnerabilities into an application.
2765+
28282766
[RFC 4648, Section 5]: https://tools.ietf.org/html/rfc4648#section-5
28292767
[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/
2830-
[`ArrayBuffer#slice()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice
28312768
[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
28322769
[`Buffer.alloc()`]: #buffer_class_method_buffer_alloc_size_fill_encoding
28332770
[`Buffer.allocUnsafe()`]: #buffer_class_method_buffer_allocunsafe_size
@@ -2847,6 +2784,9 @@ This value may depend on the JS engine that is being used.
28472784
[`String#lastIndexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
28482785
[`String.prototype.length`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
28492786
[`TypedArray.from()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from
2787+
[`TypedArray#set()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set
2788+
[`TypedArray#slice()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice
2789+
[`TypedArray#subarray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray
28502790
[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
28512791
[`Uint32Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array
28522792
[`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
@@ -2858,9 +2798,17 @@ This value may depend on the JS engine that is being used.
28582798
[`buf.keys()`]: #buffer_buf_keys
28592799
[`buf.length`]: #buffer_buf_length
28602800
[`buf.slice()`]: #buffer_buf_slice_start_end
2801+
[`buf.toString()`]: #buffer_buf_tostring_encoding_start_end
28612802
[`buf.values()`]: #buffer_buf_values
28622803
[`buffer.constants.MAX_LENGTH`]: #buffer_buffer_constants_max_length
28632804
[`buffer.constants.MAX_STRING_LENGTH`]: #buffer_buffer_constants_max_string_length
28642805
[`buffer.kMaxLength`]: #buffer_buffer_kmaxlength
28652806
[`util.inspect()`]: util.html#util_util_inspect_object_options
2807+
[ASCII]: https://en.wikipedia.org/wiki/ASCII
2808+
[Base64]: https://en.wikipedia.org/wiki/Base64
2809+
[ISO-8859-1]: https://en.wikipedia.org/wiki/ISO-8859-1
2810+
[UTF-8]: https://en.wikipedia.org/wiki/UTF-8
2811+
[UTF-16]: https://en.wikipedia.org/wiki/UTF-16
2812+
[binary strings]: https://developer.mozilla.org/en-US/docs/Web/API/DOMString/Binary
2813+
[endianness]: https://en.wikipedia.org/wiki/Endianness
28662814
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

0 commit comments

Comments
 (0)
Please sign in to comment.