4
4
5
5
> Stability: 2 - Stable
6
6
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 .
11
11
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.
15
16
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.
21
21
22
22
The ` Buffer ` class is within the global scope, making it unlikely that one
23
23
would need to ever use ` require('buffer').Buffer ` .
@@ -26,129 +26,33 @@ would need to ever use `require('buffer').Buffer`.
26
26
// Creates a zero-filled Buffer of length 10.
27
27
const buf1 = Buffer .alloc (10 );
28
28
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`.
30
31
const buf2 = Buffer .alloc (10 , 1 );
31
32
32
33
// Creates an uninitialized buffer of length 10.
33
34
// This is faster than calling Buffer.alloc() but the returned
34
35
// 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.
36
38
const buf3 = Buffer .allocUnsafe (10 );
37
39
38
- // Creates a Buffer containing [0x1, 0x2, 0x3 ].
40
+ // Creates a Buffer containing the bytes [1, 2, 3 ].
39
41
const buf4 = Buffer .from ([1 , 2 , 3 ]);
40
42
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' ]);
43
46
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' );
114
51
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' );
137
54
```
138
55
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
-
152
56
## Buffers and Character Encodings
153
57
<!-- YAML
154
58
changes:
@@ -160,48 +64,76 @@ changes:
160
64
description: Removed the deprecated `raw` and `raws` encodings.
161
65
-->
162
66
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.
165
70
166
71
``` js
167
- const buf = Buffer .from (' hello world' , ' ascii ' );
72
+ const buf = Buffer .from (' hello world' , ' utf8 ' );
168
73
169
74
console .log (buf .toString (' hex' ));
170
75
// Prints: 68656c6c6f20776f726c64
171
76
console .log (buf .toString (' base64' ));
172
77
// Prints: aGVsbG8gd29ybGQ=
173
78
174
- console .log (Buffer .from (' fhqwhgads' , ' ascii ' ));
79
+ console .log (Buffer .from (' fhqwhgads' , ' utf8 ' ));
175
80
// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
176
81
console .log (Buffer .from (' fhqwhgads' , ' utf16le' ));
177
82
// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>
178
83
```
179
84
180
- The character encodings currently supported by Node.js include :
85
+ The character encodings currently supported by Node.js are the following :
181
86
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.
184
92
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] [ ] .
187
96
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.
190
101
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.
192
104
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,
194
111
this encoding will also correctly accept "URL and Filename Safe Alphabet" as
195
112
specified in [ RFC 4648, Section 5] [ ] .
196
113
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:
200
119
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.
202
128
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.
205
137
206
138
``` js
207
139
Buffer .from (' 1ag' , ' hex' );
@@ -222,34 +154,54 @@ the WHATWG specification it is possible that the server actually returned
222
154
` 'win-1252' ` -encoded data, and using ` 'latin1' ` encoding may incorrectly decode
223
155
the characters.
224
156
225
- ## Buffers and TypedArray
157
+ ## Buffers and TypedArrays
226
158
<!-- YAML
227
159
changes:
228
160
- version: v3.0.0
229
161
pr-url: https://github.com/nodejs/node/pull/2002
230
162
description: The `Buffer`s class now inherits from `Uint8Array`.
231
163
-->
232
164
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:
238
172
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.
241
181
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 ` .
243
183
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,
246
187
` 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] ` .
249
190
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.
253
205
254
206
``` js
255
207
const arr = new Uint16Array (2 );
@@ -326,298 +278,101 @@ Additionally, the [`buf.values()`][], [`buf.keys()`][], and
326
278
The ` Buffer ` class is a global type for dealing with binary data directly.
327
279
It can be constructed in a variety of ways.
328
280
329
- ### ` new Buffer(array )`
281
+ ### Class Method: ` Buffer.alloc(size[, fill[, encoding]] ) `
330
282
<!-- YAML
331
- deprecated: v6.0 .0
283
+ added: v5.10 .0
332
284
changes:
333
285
- 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.
343
297
-->
344
298
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' ` .
348
304
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.
350
307
351
308
``` 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>
354
313
```
355
314
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.
375
318
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()` ] .
379
321
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' );
385
324
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
+ ```
390
328
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()` ] .
393
331
394
332
``` 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' );
402
334
403
335
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
+ ```
405
338
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.
408
343
409
- console .log (buf);
410
- // Prints: <Buffer 88 13 70 17>
411
- ```
344
+ A ` TypeError ` will be thrown if ` size ` is not a number.
412
345
413
- ### ` new Buffer(buffer )`
346
+ ### Class Method: ` Buffer.allocUnsafe(size ) `
414
347
<!-- YAML
415
- deprecated: v6.0 .0
348
+ added: v5.10 .0
416
349
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.
424
350
- 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 .
427
353
-->
428
354
429
- > Stability: 0 - Deprecated: Use [ ` Buffer.from(buffer) ` ] [ ] instead .
355
+ * ` size ` {integer} The desired length of the new ` Buffer ` .
430
356
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.
433
360
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.
435
365
436
366
``` js
437
- const buf1 = new Buffer (' buffer' );
438
- const buf2 = new Buffer (buf1);
367
+ const buf = Buffer .allocUnsafe (10 );
439
368
440
- buf1[0 ] = 0x61 ;
369
+ console .log (buf);
370
+ // Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
441
371
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>
621
376
```
622
377
623
378
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
657
412
allows applications to avoid the garbage collection overhead of creating many
658
413
individually allocated ` Buffer ` instances. This approach improves both
659
414
performance and memory usage by eliminating the need to track and clean up as
660
- many persistent objects.
415
+ many individual ` ArrayBuffer ` objects.
661
416
662
417
However, in the case where a developer may need to retain a small chunk of
663
418
memory from a pool for an indeterminate amount of time, it may be appropriate
@@ -682,9 +437,6 @@ socket.on('readable', () => {
682
437
});
683
438
```
684
439
685
- ` Buffer.allocUnsafeSlow() ` should be used only as a last resort after a
686
- developer has observed undue memory retention in their applications.
687
-
688
440
A ` TypeError ` will be thrown if ` size ` is not a number.
689
441
690
442
### Class Method: ` Buffer.byteLength(string[, encoding]) `
@@ -706,12 +458,12 @@ changes:
706
458
** Default:** ` 'utf8' ` .
707
459
* Returns: {integer} The number of bytes contained within ` string ` .
708
460
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 .
712
464
713
465
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
715
467
greater than the length of a ` Buffer ` created from the string.
716
468
717
469
``` js
@@ -723,7 +475,8 @@ console.log(`${str}: ${str.length} characters, ` +
723
475
```
724
476
725
477
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.
727
480
728
481
### Class Method: ` Buffer.compare(buf1, buf2) `
729
482
<!-- YAML
@@ -736,9 +489,10 @@ changes:
736
489
737
490
* ` buf1 ` {Buffer|Uint8Array}
738
491
* ` 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.
740
494
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
742
496
` Buffer ` instances. This is equivalent to calling
743
497
[ ` buf1.compare(buf2) ` ] [ `buf.compare()` ] .
744
498
@@ -762,7 +516,7 @@ changes:
762
516
-->
763
517
764
518
* ` list ` {Buffer[ ] | Uint8Array[ ] } List of ` Buffer ` or [ ` Uint8Array ` ] [ ]
765
- instances to concat .
519
+ instances to concatenate .
766
520
* ` totalLength ` {integer} Total length of the ` Buffer ` instances in ` list `
767
521
when concatenated.
768
522
* Returns: {Buffer}
@@ -774,9 +528,7 @@ If the list has no items, or if the `totalLength` is 0, then a new zero-length
774
528
` Buffer ` is returned.
775
529
776
530
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.
780
532
781
533
If ` totalLength ` is provided, it is coerced to an unsigned integer. If the
782
534
combined length of the ` Buffer ` s in ` list ` exceeds ` totalLength ` , the result is
@@ -808,10 +560,11 @@ added: v5.10.0
808
560
809
561
* ` array ` {integer[ ] }
810
562
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.
812
565
813
566
``` 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'.
815
568
const buf = Buffer .from ([0x62 , 0x75 , 0x66 , 0x66 , 0x65 , 0x72 ]);
816
569
```
817
570
@@ -824,7 +577,8 @@ added: v5.10.0
824
577
-->
825
578
826
579
* ` 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 ` ] [ ] .
828
582
* ` byteOffset ` {integer} Index of first byte to expose. ** Default:** ` 0 ` .
829
583
* ` length ` {integer} Number of bytes to expose.
830
584
** Default:** ` arrayBuffer.byteLength - byteOffset ` .
@@ -938,7 +692,7 @@ added: v5.10.0
938
692
* ` encoding ` {string} The encoding of ` string ` . ** Default:** ` 'utf8' ` .
939
693
940
694
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 .
942
696
943
697
``` js
944
698
const buf1 = Buffer .from (' this is a tést' );
@@ -948,8 +702,8 @@ console.log(buf1.toString());
948
702
// Prints: this is a tést
949
703
console .log (buf2 .toString ());
950
704
// 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
953
707
```
954
708
955
709
A ` TypeError ` will be thrown if ` string ` is not a string or other type
@@ -973,8 +727,8 @@ added: v0.9.1
973
727
* ` encoding ` {string} A character encoding name to check.
974
728
* Returns: {boolean}
975
729
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.
978
732
979
733
``` js
980
734
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
1013
767
range is between ` 0x00 ` and ` 0xFF ` (hex) or ` 0 ` and ` 255 ` (decimal).
1014
768
1015
769
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 ` .
1018
774
1019
775
``` js
1020
776
// 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.)
1021
779
1022
780
const str = ' Node.js' ;
1023
781
const buf = Buffer .allocUnsafe (str .length );
@@ -1026,7 +784,7 @@ for (let i = 0; i < str.length; i++) {
1026
784
buf[i] = str .charCodeAt (i);
1027
785
}
1028
786
1029
- console .log (buf .toString (' ascii ' ));
787
+ console .log (buf .toString (' utf8 ' ));
1030
788
// Prints: Node.js
1031
789
```
1032
790
@@ -1051,23 +809,24 @@ console.log(buffer.buffer === arrayBuffer);
1051
809
* {integer} The ` byteOffset ` on the underlying ` ArrayBuffer ` object based on
1052
810
which this ` Buffer ` object is created.
1053
811
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
1056
814
buffer doesn't start from a zero offset on the underlying ` ArrayBuffer ` .
1057
815
1058
816
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
1060
818
to the ` buf ` object itself.
1061
819
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:
1064
822
1065
823
``` js
1066
824
// Create a buffer smaller than `Buffer.poolSize`.
1067
825
const nodeBuffer = new Buffer.from ([0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]);
1068
826
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`.
1071
830
new Int8Array (nodeBuffer .buffer , nodeBuffer .byteOffset , nodeBuffer .length );
1072
831
```
1073
832
@@ -1156,9 +915,13 @@ added: v0.1.90
1156
915
inclusive). ** Default:** [ ` buf.length ` ] [ ] .
1157
916
* Returns: {integer} The number of bytes copied.
1158
917
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 `
1160
919
memory region overlaps with ` buf ` .
1161
920
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
+
1162
925
``` js
1163
926
// Create two `Buffer` instances.
1164
927
const buf1 = Buffer .allocUnsafe (26 );
@@ -1171,6 +934,8 @@ for (let i = 0; i < 26; i++) {
1171
934
1172
935
// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
1173
936
buf1 .copy (buf2, 8 , 16 , 20 );
937
+ // This is equivalent to:
938
+ // buf2.set(buf1.subarray(16, 20), 8);
1174
939
1175
940
console .log (buf2 .toString (' ascii' , 0 , 25 ));
1176
941
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
@@ -1234,7 +999,8 @@ changes:
1234
999
* Returns: {boolean}
1235
1000
1236
1001
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()` ] .
1238
1004
1239
1005
``` js
1240
1006
const buf1 = Buffer .from (' ABC' );
@@ -1299,10 +1065,10 @@ If the final write of a `fill()` operation falls on a multi-byte character,
1299
1065
then only the bytes of that character that fit into ` buf ` are written:
1300
1066
1301
1067
``` js
1302
- // Fill a `Buffer` with a two-byte character .
1068
+ // Fill a `Buffer` with character that takes up two bytes in UTF-8 .
1303
1069
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 >
1306
1072
```
1307
1073
1308
1074
If ` value ` contains invalid characters, it is truncated; if no valid
@@ -1543,42 +1309,22 @@ added: v0.1.90
1543
1309
1544
1310
* {integer}
1545
1311
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 ` .
1548
1313
1549
1314
``` 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 .
1551
1316
1552
1317
const buf = Buffer .alloc (1234 );
1553
1318
1554
1319
console .log (buf .length );
1555
1320
// Prints: 1234
1556
1321
1557
- buf .write (' some string' , 0 , ' ascii ' );
1322
+ buf .write (' some string' , 0 , ' utf8 ' );
1558
1323
1559
1324
console .log (buf .length );
1560
1325
// Prints: 1234
1561
1326
```
1562
1327
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
-
1582
1328
### ` buf.parent `
1583
1329
<!-- YAML
1584
1330
deprecated: v8.0.0
@@ -1599,8 +1345,8 @@ added: v12.0.0
1599
1345
* Returns: {bigint}
1600
1346
1601
1347
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).
1604
1350
1605
1351
Integers read from a ` Buffer ` are interpreted as two's complement signed values.
1606
1352
@@ -1615,8 +1361,8 @@ added: v12.0.0
1615
1361
* Returns: {bigint}
1616
1362
1617
1363
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).
1620
1366
1621
1367
``` js
1622
1368
const buf = Buffer .from ([0x00 , 0x00 , 0x00 , 0x00 , 0xff , 0xff , 0xff , 0xff ]);
@@ -1643,8 +1389,8 @@ changes:
1643
1389
satisfy ` 0 <= offset <= buf.length - 8 ` . ** Default:** ` 0 ` .
1644
1390
* Returns: {number}
1645
1391
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
1648
1394
little endian).
1649
1395
1650
1396
``` js
@@ -1673,8 +1419,8 @@ changes:
1673
1419
satisfy ` 0 <= offset <= buf.length - 4 ` . ** Default:** ` 0 ` .
1674
1420
* Returns: {number}
1675
1421
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
1678
1424
little endian).
1679
1425
1680
1426
``` js
@@ -1733,8 +1479,8 @@ changes:
1733
1479
* Returns: {integer}
1734
1480
1735
1481
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).
1738
1484
1739
1485
Integers read from a ` Buffer ` are interpreted as two's complement signed values.
1740
1486
@@ -1765,8 +1511,8 @@ changes:
1765
1511
* Returns: {integer}
1766
1512
1767
1513
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).
1770
1516
1771
1517
Integers read from a ` Buffer ` are interpreted as two's complement signed values.
1772
1518
@@ -1858,8 +1604,8 @@ changes:
1858
1604
* Returns: {integer}
1859
1605
1860
1606
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).
1863
1609
1864
1610
``` js
1865
1611
const buf = Buffer .from ([0x12 , 0x34 , 0x56 ]);
@@ -1892,8 +1638,8 @@ changes:
1892
1638
* Returns: {integer}
1893
1639
1894
1640
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).
1897
1643
1898
1644
``` js
1899
1645
const buf = Buffer .from ([0x12 , 0x34 , 0x56 , 0x78 ]);
@@ -1954,6 +1700,8 @@ offset and cropped by the `start` and `end` indices.
1954
1700
Specifying ` end ` greater than [ ` buf.length ` ] [ ] will return the same result as
1955
1701
that of ` end ` equal to [ ` buf.length ` ] [ ] .
1956
1702
1703
+ This method is inherited from [ ` TypedArray#subarray() ` ] [ ] .
1704
+
1957
1705
Modifying the new ` Buffer ` slice will modify the memory in the original ` Buffer `
1958
1706
because the allocated memory of the two objects overlap.
1959
1707
@@ -2129,9 +1877,6 @@ buf2.swap64();
2129
1877
// Throws ERR_INVALID_BUFFER_SIZE.
2130
1878
```
2131
1879
2132
- JavaScript cannot encode 64-bit integers. This method is intended
2133
- for working with 64-bit floats.
2134
-
2135
1880
### ` buf.toJSON() `
2136
1881
<!-- YAML
2137
1882
added: v0.9.2
@@ -2142,6 +1887,9 @@ added: v0.9.2
2142
1887
Returns a JSON representation of ` buf ` . [ ` JSON.stringify() ` ] [ ] implicitly calls
2143
1888
this function when stringifying a ` Buffer ` instance.
2144
1889
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
+
2145
1893
``` js
2146
1894
const buf = Buffer .from ([0x1 , 0x2 , 0x3 , 0x4 , 0x5 ]);
2147
1895
const json = JSON .stringify (buf);
@@ -2151,7 +1899,7 @@ console.log(json);
2151
1899
2152
1900
const copy = JSON .parse (json, (key , value ) => {
2153
1901
return value && value .type === ' Buffer' ?
2154
- Buffer .from (value . data ) :
1902
+ Buffer .from (value) :
2155
1903
value;
2156
1904
});
2157
1905
@@ -2172,8 +1920,9 @@ added: v0.1.90
2172
1920
2173
1921
Decodes ` buf ` to a string according to the specified character encoding in
2174
1922
` 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 ` .
2177
1926
2178
1927
The maximum length of a string instance (in UTF-16 code units) is available
2179
1928
as [ ` buffer.constants.MAX_STRING_LENGTH ` ] [ ] .
@@ -2186,9 +1935,9 @@ for (let i = 0; i < 26; i++) {
2186
1935
buf1[i] = i + 97 ;
2187
1936
}
2188
1937
2189
- console .log (buf1 .toString (' ascii ' ));
1938
+ console .log (buf1 .toString (' utf8 ' ));
2190
1939
// Prints: abcdefghijklmnopqrstuvwxyz
2191
- console .log (buf1 .toString (' ascii ' , 0 , 5 ));
1940
+ console .log (buf1 .toString (' utf8 ' , 0 , 5 ));
2192
1941
// Prints: abcde
2193
1942
2194
1943
const buf2 = Buffer .from (' tést' );
@@ -2245,7 +1994,7 @@ added: v0.1.90
2245
1994
* ` string ` {string} String to write to ` buf ` .
2246
1995
* ` offset ` {integer} Number of bytes to skip before starting to write ` string ` .
2247
1996
** Default:** ` 0 ` .
2248
- * ` length ` {integer} Number of bytes to write. ** Default:**
1997
+ * ` length ` {integer} Maximum number of bytes to write. ** Default:**
2249
1998
` buf.length - offset ` .
2250
1999
* ` encoding ` {string} The character encoding of ` string ` . ** Default:** ` 'utf8' ` .
2251
2000
* Returns: {integer} Number of bytes written.
@@ -2275,9 +2024,9 @@ added: v12.0.0
2275
2024
satisfy: ` 0 <= offset <= buf.length - 8 ` . ** Default:** ` 0 ` .
2276
2025
* Returns: {integer} ` offset ` plus the number of bytes written.
2277
2026
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).
2281
2030
2282
2031
` value ` is interpreted and written as a two's complement signed integer.
2283
2032
@@ -2301,8 +2050,8 @@ added: v12.0.0
2301
2050
satisfy: ` 0 <= offset <= buf.length - 8 ` . ** Default:** ` 0 ` .
2302
2051
* Returns: {integer} ` offset ` plus the number of bytes written.
2303
2052
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
2306
2055
little endian).
2307
2056
2308
2057
``` js
@@ -2330,10 +2079,10 @@ changes:
2330
2079
satisfy ` 0 <= offset <= buf.length - 8 ` . ** Default:** ` 0 ` .
2331
2080
* Returns: {integer} ` offset ` plus the number of bytes written.
2332
2081
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 .
2337
2086
2338
2087
``` js
2339
2088
const buf = Buffer .allocUnsafe (8 );
@@ -2365,10 +2114,10 @@ changes:
2365
2114
satisfy ` 0 <= offset <= buf.length - 4 ` . ** Default:** ` 0 ` .
2366
2115
* Returns: {integer} ` offset ` plus the number of bytes written.
2367
2116
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 .
2372
2121
2373
2122
``` js
2374
2123
const buf = Buffer .allocUnsafe (4 );
@@ -2399,7 +2148,7 @@ changes:
2399
2148
satisfy ` 0 <= offset <= buf.length - 1 ` . ** Default:** ` 0 ` .
2400
2149
* Returns: {integer} ` offset ` plus the number of bytes written.
2401
2150
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
2403
2152
signed 8-bit integer. Behavior is undefined when ` value ` is anything other than
2404
2153
a signed 8-bit integer.
2405
2154
@@ -2431,9 +2180,9 @@ changes:
2431
2180
satisfy ` 0 <= offset <= buf.length - 2 ` . ** Default:** ` 0 ` .
2432
2181
* Returns: {integer} ` offset ` plus the number of bytes written.
2433
2182
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
2437
2186
undefined when ` value ` is anything other than a signed 16-bit integer.
2438
2187
2439
2188
` value ` is interpreted and written as a two's complement signed integer.
@@ -2464,9 +2213,9 @@ changes:
2464
2213
satisfy ` 0 <= offset <= buf.length - 4 ` . ** Default:** ` 0 ` .
2465
2214
* Returns: {integer} ` offset ` plus the number of bytes written.
2466
2215
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
2470
2219
undefined when ` value ` is anything other than a signed 32-bit integer.
2471
2220
2472
2221
` value ` is interpreted and written as a two's complement signed integer.
@@ -2532,7 +2281,7 @@ changes:
2532
2281
satisfy ` 0 <= offset <= buf.length - 1 ` . ** Default:** ` 0 ` .
2533
2282
* Returns: {integer} ` offset ` plus the number of bytes written.
2534
2283
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
2536
2285
valid unsigned 8-bit integer. Behavior is undefined when ` value ` is anything
2537
2286
other than an unsigned 8-bit integer.
2538
2287
@@ -2564,9 +2313,9 @@ changes:
2564
2313
satisfy ` 0 <= offset <= buf.length - 2 ` . ** Default:** ` 0 ` .
2565
2314
* Returns: {integer} ` offset ` plus the number of bytes written.
2566
2315
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
2570
2319
undefined when ` value ` is anything other than an unsigned 16-bit integer.
2571
2320
2572
2321
``` js
@@ -2601,9 +2350,9 @@ changes:
2601
2350
satisfy ` 0 <= offset <= buf.length - 4 ` . ** Default:** ` 0 ` .
2602
2351
* Returns: {integer} ` offset ` plus the number of bytes written.
2603
2352
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
2607
2356
undefined when ` value ` is anything other than an unsigned 32-bit integer.
2608
2357
2609
2358
``` js
@@ -2656,6 +2405,138 @@ console.log(buf);
2656
2405
// Prints: <Buffer ab 90 78 56 34 12>
2657
2406
```
2658
2407
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
+
2659
2540
## ` buffer.INSPECT_MAX_BYTES `
2660
2541
<!-- YAML
2661
2542
added: v0.5.4
@@ -2729,36 +2610,9 @@ deprecated: v6.0.0
2729
2610
2730
2611
> Stability: 0 - Deprecated: Use [ ` Buffer.allocUnsafeSlow() ` ] [ ] instead.
2731
2612
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.
2762
2616
2763
2617
### ` new SlowBuffer(size) `
2764
2618
<!-- YAML
@@ -2769,28 +2623,7 @@ deprecated: v6.0.0
2769
2623
2770
2624
* ` size ` {integer} The desired length of the new ` SlowBuffer ` .
2771
2625
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() ` ] [ ] .
2794
2627
2795
2628
## Buffer Constants
2796
2629
<!-- YAML
@@ -2807,8 +2640,8 @@ added: v8.2.0
2807
2640
2808
2641
* {integer} The largest size allowed for a single ` Buffer ` instance.
2809
2642
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).
2812
2645
2813
2646
This value is also available as [ ` buffer.kMaxLength ` ] [ ] .
2814
2647
@@ -2824,10 +2657,114 @@ in UTF-16 code units.
2824
2657
2825
2658
This value may depend on the JS engine that is being used.
2826
2659
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
+
2828
2766
[ RFC 4648, Section 5 ] : https://tools.ietf.org/html/rfc4648#section-5
2829
2767
[ 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
2831
2768
[ `ArrayBuffer` ] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
2832
2769
[ `Buffer.alloc()` ] : #buffer_class_method_buffer_alloc_size_fill_encoding
2833
2770
[ `Buffer.allocUnsafe()` ] : #buffer_class_method_buffer_allocunsafe_size
@@ -2847,6 +2784,9 @@ This value may depend on the JS engine that is being used.
2847
2784
[ `String#lastIndexOf()` ] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
2848
2785
[ `String.prototype.length` ] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
2849
2786
[ `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
2850
2790
[ `TypedArray` ] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
2851
2791
[ `Uint32Array` ] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array
2852
2792
[ `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.
2858
2798
[ `buf.keys()` ] : #buffer_buf_keys
2859
2799
[ `buf.length` ] : #buffer_buf_length
2860
2800
[ `buf.slice()` ] : #buffer_buf_slice_start_end
2801
+ [ `buf.toString()` ] : #buffer_buf_tostring_encoding_start_end
2861
2802
[ `buf.values()` ] : #buffer_buf_values
2862
2803
[ `buffer.constants.MAX_LENGTH` ] : #buffer_buffer_constants_max_length
2863
2804
[ `buffer.constants.MAX_STRING_LENGTH` ] : #buffer_buffer_constants_max_string_length
2864
2805
[ `buffer.kMaxLength` ] : #buffer_buffer_kmaxlength
2865
2806
[ `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
2866
2814
[ iterator ] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
0 commit comments