-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
buffer.md
5541 lines (4116 loc) · 149 KB
/
buffer.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Buffer
<!--introduced_in=v0.1.90-->
> Stability: 2 - Stable
<!-- source_link=lib/buffer.js -->
`Buffer` objects are used to represent a fixed-length sequence of bytes. Many
Node.js APIs support `Buffer`s.
The `Buffer` class is a subclass of JavaScript's [`Uint8Array`][] class and
extends it with methods that cover additional use cases. Node.js APIs accept
plain [`Uint8Array`][]s wherever `Buffer`s are supported as well.
While the `Buffer` class is available within the global scope, it is still
recommended to explicitly reference it via an import or require statement.
```mjs
import { Buffer } from 'node:buffer';
// Creates a zero-filled Buffer of length 10.
const buf1 = Buffer.alloc(10);
// Creates a Buffer of length 10,
// filled with bytes which all have the value `1`.
const buf2 = Buffer.alloc(10, 1);
// Creates an uninitialized buffer of length 10.
// This is faster than calling Buffer.alloc() but the returned
// Buffer instance might contain old data that needs to be
// overwritten using fill(), write(), or other functions that fill the Buffer's
// contents.
const buf3 = Buffer.allocUnsafe(10);
// Creates a Buffer containing the bytes [1, 2, 3].
const buf4 = Buffer.from([1, 2, 3]);
// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
// are all truncated using `(value & 255)` to fit into the range 0–255.
const buf5 = Buffer.from([257, 257.5, -255, '1']);
// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
// [116, 195, 169, 115, 116] (in decimal notation)
const buf6 = Buffer.from('tést');
// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf7 = Buffer.from('tést', 'latin1');
```
```cjs
const { Buffer } = require('node:buffer');
// Creates a zero-filled Buffer of length 10.
const buf1 = Buffer.alloc(10);
// Creates a Buffer of length 10,
// filled with bytes which all have the value `1`.
const buf2 = Buffer.alloc(10, 1);
// Creates an uninitialized buffer of length 10.
// This is faster than calling Buffer.alloc() but the returned
// Buffer instance might contain old data that needs to be
// overwritten using fill(), write(), or other functions that fill the Buffer's
// contents.
const buf3 = Buffer.allocUnsafe(10);
// Creates a Buffer containing the bytes [1, 2, 3].
const buf4 = Buffer.from([1, 2, 3]);
// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
// are all truncated using `(value & 255)` to fit into the range 0–255.
const buf5 = Buffer.from([257, 257.5, -255, '1']);
// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
// [116, 195, 169, 115, 116] (in decimal notation)
const buf6 = Buffer.from('tést');
// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf7 = Buffer.from('tést', 'latin1');
```
## Buffers and character encodings
<!-- YAML
changes:
- version:
- v15.7.0
- v14.18.0
pr-url: https://github.com/nodejs/node/pull/36952
description: Introduced `base64url` encoding.
- version: v6.4.0
pr-url: https://github.com/nodejs/node/pull/7111
description: Introduced `latin1` as an alias for `binary`.
- version: v5.0.0
pr-url: https://github.com/nodejs/node/pull/2859
description: Removed the deprecated `raw` and `raws` encodings.
-->
When converting between `Buffer`s and strings, a character encoding may be
specified. If no character encoding is specified, UTF-8 will be used as the
default.
```mjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello world', 'utf8');
console.log(buf.toString('hex'));
// Prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64'));
// Prints: aGVsbG8gd29ybGQ=
console.log(Buffer.from('fhqwhgads', 'utf8'));
// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
console.log(Buffer.from('fhqwhgads', 'utf16le'));
// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>
```
```cjs
const { Buffer } = require('node:buffer');
const buf = Buffer.from('hello world', 'utf8');
console.log(buf.toString('hex'));
// Prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64'));
// Prints: aGVsbG8gd29ybGQ=
console.log(Buffer.from('fhqwhgads', 'utf8'));
// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
console.log(Buffer.from('fhqwhgads', 'utf16le'));
// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>
```
Node.js buffers accept all case variations of encoding strings that they
receive. For example, UTF-8 can be specified as `'utf8'`, `'UTF8'`, or `'uTf8'`.
The character encodings currently supported by Node.js are the following:
* `'utf8'` (alias: `'utf-8'`): Multi-byte encoded Unicode characters. Many web
pages and other document formats use [UTF-8][]. This is the default character
encoding. When decoding a `Buffer` into a string that does not exclusively
contain valid UTF-8 data, the Unicode replacement character `U+FFFD` � will be
used to represent those errors.
* `'utf16le'` (alias: `'utf-16le'`): Multi-byte encoded Unicode characters.
Unlike `'utf8'`, each character in the string will be encoded using either 2
or 4 bytes. Node.js only supports the [little-endian][endianness] variant of
[UTF-16][].
* `'latin1'`: Latin-1 stands for [ISO-8859-1][]. This character encoding only
supports the Unicode characters from `U+0000` to `U+00FF`. Each character is
encoded using a single byte. Characters that do not fit into that range are
truncated and will be mapped to characters in that range.
Converting a `Buffer` into a string using one of the above is referred to as
decoding, and converting a string into a `Buffer` is referred to as encoding.
Node.js also supports the following binary-to-text encodings. For
binary-to-text encodings, the naming convention is reversed: Converting a
`Buffer` into a string is typically referred to as encoding, and converting a
string into a `Buffer` as decoding.
* `'base64'`: [Base64][] encoding. When creating a `Buffer` from a string,
this encoding will also correctly accept "URL and Filename Safe Alphabet" as
specified in [RFC 4648, Section 5][]. Whitespace characters such as spaces,
tabs, and new lines contained within the base64-encoded string are ignored.
* `'base64url'`: [base64url][] encoding as specified in
[RFC 4648, Section 5][]. When creating a `Buffer` from a string, this
encoding will also correctly accept regular base64-encoded strings. When
encoding a `Buffer` to a string, this encoding will omit padding.
* `'hex'`: Encode each byte as two hexadecimal characters. Data truncation
may occur when decoding strings that do not exclusively consist of an even
number of hexadecimal characters. See below for an example.
The following legacy character encodings are also supported:
* `'ascii'`: For 7-bit [ASCII][] data only. When encoding a string into a
`Buffer`, this is equivalent to using `'latin1'`. When decoding a `Buffer`
into a string, using this encoding will additionally unset the highest bit of
each byte before decoding as `'latin1'`.
Generally, there should be no reason to use this encoding, as `'utf8'`
(or, if the data is known to always be ASCII-only, `'latin1'`) will be a
better choice when encoding or decoding ASCII-only text. It is only provided
for legacy compatibility.
* `'binary'`: Alias for `'latin1'`.
The name of this encoding can be very misleading, as all of the
encodings listed here convert between strings and binary data. For converting
between strings and `Buffer`s, typically `'utf8'` is the right choice.
* `'ucs2'`, `'ucs-2'`: Aliases of `'utf16le'`. UCS-2 used to refer to a variant
of UTF-16 that did not support characters that had code points larger than
U+FFFF. In Node.js, these code points are always supported.
```mjs
import { Buffer } from 'node:buffer';
Buffer.from('1ag123', 'hex');
// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
// ('g') encountered.
Buffer.from('1a7', 'hex');
// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').
Buffer.from('1634', 'hex');
// Prints <Buffer 16 34>, all data represented.
```
```cjs
const { Buffer } = require('node:buffer');
Buffer.from('1ag123', 'hex');
// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
// ('g') encountered.
Buffer.from('1a7', 'hex');
// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').
Buffer.from('1634', 'hex');
// Prints <Buffer 16 34>, all data represented.
```
Modern Web browsers follow the [WHATWG Encoding Standard][] which aliases
both `'latin1'` and `'ISO-8859-1'` to `'win-1252'`. This means that while doing
something like `http.get()`, if the returned charset is one of those listed in
the WHATWG specification it is possible that the server actually returned
`'win-1252'`-encoded data, and using `'latin1'` encoding may incorrectly decode
the characters.
## Buffers and TypedArrays
<!-- YAML
changes:
- version: v3.0.0
pr-url: https://github.com/nodejs/node/pull/2002
description: The `Buffer`s class now inherits from `Uint8Array`.
-->
`Buffer` instances are also JavaScript [`Uint8Array`][] and [`TypedArray`][]
instances. All [`TypedArray`][] methods are available on `Buffer`s. There are,
however, subtle incompatibilities between the `Buffer` API and the
[`TypedArray`][] API.
In particular:
* While [`TypedArray.prototype.slice()`][] creates a copy of part of the `TypedArray`,
[`Buffer.prototype.slice()`][`buf.slice()`] creates a view over the existing `Buffer`
without copying. This behavior can be surprising, and only exists for legacy
compatibility. [`TypedArray.prototype.subarray()`][] can be used to achieve
the behavior of [`Buffer.prototype.slice()`][`buf.slice()`] on both `Buffer`s
and other `TypedArray`s and should be preferred.
* [`buf.toString()`][] is incompatible with its `TypedArray` equivalent.
* A number of methods, e.g. [`buf.indexOf()`][], support additional arguments.
There are two ways to create new [`TypedArray`][] instances from a `Buffer`:
* Passing a `Buffer` to a [`TypedArray`][] constructor will copy the `Buffer`s
contents, interpreted as an array of integers, and not as a byte sequence
of the target type.
```mjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
const uint32array = new Uint32Array(buf);
console.log(uint32array);
// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
```
```cjs
const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4]);
const uint32array = new Uint32Array(buf);
console.log(uint32array);
// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
```
* Passing the `Buffer`s underlying [`ArrayBuffer`][] will create a
[`TypedArray`][] that shares its memory with the `Buffer`.
```mjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello', 'utf16le');
const uint16array = new Uint16Array(
buf.buffer,
buf.byteOffset,
buf.length / Uint16Array.BYTES_PER_ELEMENT);
console.log(uint16array);
// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
```
```cjs
const { Buffer } = require('node:buffer');
const buf = Buffer.from('hello', 'utf16le');
const uint16array = new Uint16Array(
buf.buffer,
buf.byteOffset,
buf.length / Uint16Array.BYTES_PER_ELEMENT);
console.log(uint16array);
// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
```
It is possible to create a new `Buffer` that shares the same allocated
memory as a [`TypedArray`][] instance by using the `TypedArray` object's
`.buffer` property in the same way. [`Buffer.from()`][`Buffer.from(arrayBuf)`]
behaves like `new Uint8Array()` in this context.
```mjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);
// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 a0 0f>
arr[1] = 6000;
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 70 17>
```
```cjs
const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);
// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 a0 0f>
arr[1] = 6000;
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 70 17>
```
When creating a `Buffer` using a [`TypedArray`][]'s `.buffer`, it is
possible to use only a portion of the underlying [`ArrayBuffer`][] by passing in
`byteOffset` and `length` parameters.
```mjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(20);
const buf = Buffer.from(arr.buffer, 0, 16);
console.log(buf.length);
// Prints: 16
```
```cjs
const { Buffer } = require('node:buffer');
const arr = new Uint16Array(20);
const buf = Buffer.from(arr.buffer, 0, 16);
console.log(buf.length);
// Prints: 16
```
The `Buffer.from()` and [`TypedArray.from()`][] have different signatures and
implementations. Specifically, the [`TypedArray`][] variants accept a second
argument that is a mapping function that is invoked on every element of the
typed array:
* `TypedArray.from(source[, mapFn[, thisArg]])`
The `Buffer.from()` method, however, does not support the use of a mapping
function:
* [`Buffer.from(array)`][]
* [`Buffer.from(buffer)`][]
* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`]
## Buffers and iteration
`Buffer` instances can be iterated over using `for..of` syntax:
```mjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3]);
for (const b of buf) {
console.log(b);
}
// Prints:
// 1
// 2
// 3
```
```cjs
const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3]);
for (const b of buf) {
console.log(b);
}
// Prints:
// 1
// 2
// 3
```
Additionally, the [`buf.values()`][], [`buf.keys()`][], and
[`buf.entries()`][] methods can be used to create iterators.
## Class: `Blob`
<!-- YAML
added:
- v15.7.0
- v14.18.0
changes:
- version:
- v18.0.0
- v16.17.0
pr-url: https://github.com/nodejs/node/pull/41270
description: No longer experimental.
-->
A [`Blob`][] encapsulates immutable, raw data that can be safely shared across
multiple worker threads.
### `new buffer.Blob([sources[, options]])`
<!-- YAML
added:
- v15.7.0
- v14.18.0
changes:
- version: v16.7.0
pr-url: https://github.com/nodejs/node/pull/39708
description: Added the standard `endings` option to replace line-endings,
and removed the non-standard `encoding` option.
-->
* `sources` {string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[]} An
array of string, {ArrayBuffer}, {TypedArray}, {DataView}, or {Blob} objects,
or any mix of such objects, that will be stored within the `Blob`.
* `options` {Object}
* `endings` {string} One of either `'transparent'` or `'native'`. When set
to `'native'`, line endings in string source parts will be converted to
the platform native line-ending as specified by `require('node:os').EOL`.
* `type` {string} The Blob content-type. The intent is for `type` to convey
the MIME media type of the data, however no validation of the type format
is performed.
Creates a new `Blob` object containing a concatenation of the given sources.
{ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into
the 'Blob' and can therefore be safely modified after the 'Blob' is created.
String sources are encoded as UTF-8 byte sequences and copied into the Blob.
Unmatched surrogate pairs within each string part will be replaced by Unicode
U+FFFD replacement characters.
### `blob.arrayBuffer()`
<!-- YAML
added:
- v15.7.0
- v14.18.0
-->
* Returns: {Promise}
Returns a promise that fulfills with an {ArrayBuffer} containing a copy of
the `Blob` data.
### `blob.size`
<!-- YAML
added:
- v15.7.0
- v14.18.0
-->
The total size of the `Blob` in bytes.
### `blob.slice([start[, end[, type]]])`
<!-- YAML
added:
- v15.7.0
- v14.18.0
-->
* `start` {number} The starting index.
* `end` {number} The ending index.
* `type` {string} The content-type for the new `Blob`
Creates and returns a new `Blob` containing a subset of this `Blob` objects
data. The original `Blob` is not altered.
### `blob.stream()`
<!-- YAML
added: v16.7.0
-->
* Returns: {ReadableStream}
Returns a new `ReadableStream` that allows the content of the `Blob` to be read.
### `blob.text()`
<!-- YAML
added:
- v15.7.0
- v14.18.0
-->
* Returns: {Promise}
Returns a promise that fulfills with the contents of the `Blob` decoded as a
UTF-8 string.
### `blob.type`
<!-- YAML
added:
- v15.7.0
- v14.18.0
-->
* Type: {string}
The content-type of the `Blob`.
### `Blob` objects and `MessageChannel`
Once a {Blob} object is created, it can be sent via `MessagePort` to multiple
destinations without transferring or immediately copying the data. The data
contained by the `Blob` is copied only when the `arrayBuffer()` or `text()`
methods are called.
```mjs
import { Blob } from 'node:buffer';
import { setTimeout as delay } from 'node:timers/promises';
const blob = new Blob(['hello there']);
const mc1 = new MessageChannel();
const mc2 = new MessageChannel();
mc1.port1.onmessage = async ({ data }) => {
console.log(await data.arrayBuffer());
mc1.port1.close();
};
mc2.port1.onmessage = async ({ data }) => {
await delay(1000);
console.log(await data.arrayBuffer());
mc2.port1.close();
};
mc1.port2.postMessage(blob);
mc2.port2.postMessage(blob);
// The Blob is still usable after posting.
blob.text().then(console.log);
```
```cjs
const { Blob } = require('node:buffer');
const { setTimeout: delay } = require('node:timers/promises');
const blob = new Blob(['hello there']);
const mc1 = new MessageChannel();
const mc2 = new MessageChannel();
mc1.port1.onmessage = async ({ data }) => {
console.log(await data.arrayBuffer());
mc1.port1.close();
};
mc2.port1.onmessage = async ({ data }) => {
await delay(1000);
console.log(await data.arrayBuffer());
mc2.port1.close();
};
mc1.port2.postMessage(blob);
mc2.port2.postMessage(blob);
// The Blob is still usable after posting.
blob.text().then(console.log);
```
## Class: `Buffer`
The `Buffer` class is a global type for dealing with binary data directly.
It can be constructed in a variety of ways.
### Static method: `Buffer.alloc(size[, fill[, encoding]])`
<!-- YAML
added: v5.10.0
changes:
- version: v20.0.0
pr-url: https://github.com/nodejs/node/pull/45796
description: Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of
ERR_INVALID_ARG_VALUE for invalid input arguments.
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/34682
description: Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE
for invalid input arguments.
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18129
description: Attempting to fill a non-zero length buffer with a zero length
buffer triggers a thrown exception.
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/17427
description: Specifying an invalid string for `fill` triggers a thrown
exception.
- version: v8.9.3
pr-url: https://github.com/nodejs/node/pull/17428
description: Specifying an invalid string for `fill` now results in a
zero-filled buffer.
-->
* `size` {integer} The desired length of the new `Buffer`.
* `fill` {string|Buffer|Uint8Array|integer} A value to pre-fill the new `Buffer`
with. **Default:** `0`.
* `encoding` {string} If `fill` is a string, this is its encoding.
**Default:** `'utf8'`.
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
`Buffer` will be zero-filled.
```mjs
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(5);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00>
```
```cjs
const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(5);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00>
```
If `size` is larger than
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_OUT_OF_RANGE`][]
is thrown.
If `fill` is specified, the allocated `Buffer` will be initialized by calling
[`buf.fill(fill)`][`buf.fill()`].
```mjs
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(5, 'a');
console.log(buf);
// Prints: <Buffer 61 61 61 61 61>
```
```cjs
const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(5, 'a');
console.log(buf);
// Prints: <Buffer 61 61 61 61 61>
```
If both `fill` and `encoding` are specified, the allocated `Buffer` will be
initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`].
```mjs
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
```
```cjs
const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
```
Calling [`Buffer.alloc()`][] can be measurably slower than the alternative
[`Buffer.allocUnsafe()`][] but ensures that the newly created `Buffer` instance
contents will never contain sensitive data from previous allocations, including
data that might not have been allocated for `Buffer`s.
A `TypeError` will be thrown if `size` is not a number.
### Static method: `Buffer.allocUnsafe(size)`
<!-- YAML
added: v5.10.0
changes:
- version: v20.0.0
pr-url: https://github.com/nodejs/node/pull/45796
description: Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of
ERR_INVALID_ARG_VALUE for invalid input arguments.
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/34682
description: Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE
for invalid input arguments.
- version: v7.0.0
pr-url: https://github.com/nodejs/node/pull/7079
description: Passing a negative `size` will now throw an error.
-->
* `size` {integer} The desired length of the new `Buffer`.
Allocates a new `Buffer` of `size` bytes. If `size` is larger than
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_OUT_OF_RANGE`][]
is thrown.
The underlying memory for `Buffer` instances created in this way is _not
initialized_. The contents of the newly created `Buffer` are unknown and
_may contain sensitive data_. Use [`Buffer.alloc()`][] instead to initialize
`Buffer` instances with zeroes.
```mjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(10);
console.log(buf);
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
buf.fill(0);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
```
```cjs
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(10);
console.log(buf);
// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
buf.fill(0);
console.log(buf);
// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
```
A `TypeError` will be thrown if `size` is not a number.
The `Buffer` module pre-allocates an internal `Buffer` instance of
size [`Buffer.poolSize`][] that is used as a pool for the fast allocation of new
`Buffer` instances created using [`Buffer.allocUnsafe()`][], [`Buffer.from(array)`][],
[`Buffer.from(string)`][], and [`Buffer.concat()`][] only when `size` is less than
`Buffer.poolSize >>> 1` (floor of [`Buffer.poolSize`][] divided by two).
Use of this pre-allocated internal memory pool is a key difference between
calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`
pool, while `Buffer.allocUnsafe(size).fill(fill)` _will_ use the internal
`Buffer` pool if `size` is less than or equal to half [`Buffer.poolSize`][]. The
difference is subtle but can be important when an application requires the
additional performance that [`Buffer.allocUnsafe()`][] provides.
### Static method: `Buffer.allocUnsafeSlow(size)`
<!-- YAML
added: v5.12.0
changes:
- version: v20.0.0
pr-url: https://github.com/nodejs/node/pull/45796
description: Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of
ERR_INVALID_ARG_VALUE for invalid input arguments.
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/34682
description: Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE
for invalid input arguments.
-->
* `size` {integer} The desired length of the new `Buffer`.
Allocates a new `Buffer` of `size` bytes. If `size` is larger than
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_OUT_OF_RANGE`][]
is thrown. A zero-length `Buffer` is created if `size` is 0.
The underlying memory for `Buffer` instances created in this way is _not
initialized_. The contents of the newly created `Buffer` are unknown and
_may contain sensitive data_. Use [`buf.fill(0)`][`buf.fill()`] to initialize
such `Buffer` instances with zeroes.
When using [`Buffer.allocUnsafe()`][] to allocate new `Buffer` instances,
allocations less than `Buffer.poolSize >>> 1` (4KiB when default poolSize is used) are sliced
from a single pre-allocated `Buffer`. This allows applications to avoid the
garbage collection overhead of creating many individually allocated `Buffer`
instances. This approach improves both performance and memory usage by
eliminating the need to track and clean up as many individual `ArrayBuffer` objects.
However, in the case where a developer may need to retain a small chunk of
memory from a pool for an indeterminate amount of time, it may be appropriate
to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and
then copying out the relevant bits.
```mjs
import { Buffer } from 'node:buffer';
// Need to keep around a few small chunks of memory.
const store = [];
socket.on('readable', () => {
let data;
while (null !== (data = readable.read())) {
// Allocate for retained data.
const sb = Buffer.allocUnsafeSlow(10);
// Copy the data into the new allocation.
data.copy(sb, 0, 0, 10);
store.push(sb);
}
});
```
```cjs
const { Buffer } = require('node:buffer');
// Need to keep around a few small chunks of memory.
const store = [];
socket.on('readable', () => {
let data;
while (null !== (data = readable.read())) {
// Allocate for retained data.
const sb = Buffer.allocUnsafeSlow(10);
// Copy the data into the new allocation.
data.copy(sb, 0, 0, 10);
store.push(sb);
}
});
```
A `TypeError` will be thrown if `size` is not a number.
### Static method: `Buffer.byteLength(string[, encoding])`
<!-- YAML
added: v0.1.90
changes:
- version: v7.0.0
pr-url: https://github.com/nodejs/node/pull/8946
description: Passing invalid input will now throw an error.
- version: v5.10.0
pr-url: https://github.com/nodejs/node/pull/5255
description: The `string` parameter can now be any `TypedArray`, `DataView`
or `ArrayBuffer`.
-->
* `string` {string|Buffer|TypedArray|DataView|ArrayBuffer|SharedArrayBuffer} A
value to calculate the length of.
* `encoding` {string} If `string` is a string, this is its encoding.
**Default:** `'utf8'`.
* Returns: {integer} The number of bytes contained within `string`.
Returns the byte length of a string when encoded using `encoding`.
This is not the same as [`String.prototype.length`][], which does not account
for the encoding that is used to convert the string into bytes.
For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input.
For strings that contain non-base64/hex-encoded data (e.g. whitespace), the
return value might be greater than the length of a `Buffer` created from the
string.
```mjs
import { Buffer } from 'node:buffer';
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
```
```cjs
const { Buffer } = require('node:buffer');
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
```
When `string` is a `Buffer`/[`DataView`][]/[`TypedArray`][]/[`ArrayBuffer`][]/
[`SharedArrayBuffer`][], the byte length as reported by `.byteLength`
is returned.
### Static method: `Buffer.compare(buf1, buf2)`
<!-- YAML
added: v0.11.13
changes:
- version: v8.0.0
pr-url: https://github.com/nodejs/node/pull/10236
description: The arguments can now be `Uint8Array`s.
-->
* `buf1` {Buffer|Uint8Array}
* `buf2` {Buffer|Uint8Array}
* Returns: {integer} Either `-1`, `0`, or `1`, depending on the result of the
comparison. See [`buf.compare()`][] for details.
Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of
`Buffer` instances. This is equivalent to calling
[`buf1.compare(buf2)`][`buf.compare()`].
```mjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('1234');
const buf2 = Buffer.from('0123');
const arr = [buf1, buf2];
console.log(arr.sort(Buffer.compare));
// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
// (This result is equal to: [buf2, buf1].)
```
```cjs
const { Buffer } = require('node:buffer');
const buf1 = Buffer.from('1234');
const buf2 = Buffer.from('0123');
const arr = [buf1, buf2];
console.log(arr.sort(Buffer.compare));
// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
// (This result is equal to: [buf2, buf1].)
```
### Static method: `Buffer.concat(list[, totalLength])`
<!-- YAML