• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Buffer
2
3<!--introduced_in=v0.1.90-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/buffer.js -->
8
9`Buffer` objects are used to represent a fixed-length sequence of bytes. Many
10Node.js APIs support `Buffer`s.
11
12The `Buffer` class is a subclass of JavaScript's [`Uint8Array`][] class and
13extends it with methods that cover additional use cases. Node.js APIs accept
14plain [`Uint8Array`][]s wherever `Buffer`s are supported as well.
15
16While the `Buffer` class is available within the global scope, it is still
17recommended to explicitly reference it via an import or require statement.
18
19```mjs
20import { Buffer } from 'node:buffer';
21
22// Creates a zero-filled Buffer of length 10.
23const buf1 = Buffer.alloc(10);
24
25// Creates a Buffer of length 10,
26// filled with bytes which all have the value `1`.
27const buf2 = Buffer.alloc(10, 1);
28
29// Creates an uninitialized buffer of length 10.
30// This is faster than calling Buffer.alloc() but the returned
31// Buffer instance might contain old data that needs to be
32// overwritten using fill(), write(), or other functions that fill the Buffer's
33// contents.
34const buf3 = Buffer.allocUnsafe(10);
35
36// Creates a Buffer containing the bytes [1, 2, 3].
37const buf4 = Buffer.from([1, 2, 3]);
38
39// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
40// are all truncated using `(value & 255)` to fit into the range 0–255.
41const buf5 = Buffer.from([257, 257.5, -255, '1']);
42
43// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
44// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
45// [116, 195, 169, 115, 116] (in decimal notation)
46const buf6 = Buffer.from('tést');
47
48// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
49const buf7 = Buffer.from('tést', 'latin1');
50```
51
52```cjs
53const { Buffer } = require('node:buffer');
54
55// Creates a zero-filled Buffer of length 10.
56const buf1 = Buffer.alloc(10);
57
58// Creates a Buffer of length 10,
59// filled with bytes which all have the value `1`.
60const buf2 = Buffer.alloc(10, 1);
61
62// Creates an uninitialized buffer of length 10.
63// This is faster than calling Buffer.alloc() but the returned
64// Buffer instance might contain old data that needs to be
65// overwritten using fill(), write(), or other functions that fill the Buffer's
66// contents.
67const buf3 = Buffer.allocUnsafe(10);
68
69// Creates a Buffer containing the bytes [1, 2, 3].
70const buf4 = Buffer.from([1, 2, 3]);
71
72// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
73// are all truncated using `(value & 255)` to fit into the range 0–255.
74const buf5 = Buffer.from([257, 257.5, -255, '1']);
75
76// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
77// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
78// [116, 195, 169, 115, 116] (in decimal notation)
79const buf6 = Buffer.from('tést');
80
81// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
82const buf7 = Buffer.from('tést', 'latin1');
83```
84
85## Buffers and character encodings
86
87<!-- YAML
88changes:
89  - version:
90      - v15.7.0
91      - v14.18.0
92    pr-url: https://github.com/nodejs/node/pull/36952
93    description: Introduced `base64url` encoding.
94  - version: v6.4.0
95    pr-url: https://github.com/nodejs/node/pull/7111
96    description: Introduced `latin1` as an alias for `binary`.
97  - version: v5.0.0
98    pr-url: https://github.com/nodejs/node/pull/2859
99    description: Removed the deprecated `raw` and `raws` encodings.
100-->
101
102When converting between `Buffer`s and strings, a character encoding may be
103specified. If no character encoding is specified, UTF-8 will be used as the
104default.
105
106```mjs
107import { Buffer } from 'node:buffer';
108
109const buf = Buffer.from('hello world', 'utf8');
110
111console.log(buf.toString('hex'));
112// Prints: 68656c6c6f20776f726c64
113console.log(buf.toString('base64'));
114// Prints: aGVsbG8gd29ybGQ=
115
116console.log(Buffer.from('fhqwhgads', 'utf8'));
117// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
118console.log(Buffer.from('fhqwhgads', 'utf16le'));
119// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>
120```
121
122```cjs
123const { Buffer } = require('node:buffer');
124
125const buf = Buffer.from('hello world', 'utf8');
126
127console.log(buf.toString('hex'));
128// Prints: 68656c6c6f20776f726c64
129console.log(buf.toString('base64'));
130// Prints: aGVsbG8gd29ybGQ=
131
132console.log(Buffer.from('fhqwhgads', 'utf8'));
133// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
134console.log(Buffer.from('fhqwhgads', 'utf16le'));
135// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>
136```
137
138Node.js buffers accept all case variations of encoding strings that they
139receive. For example, UTF-8 can be specified as `'utf8'`, `'UTF8'`, or `'uTf8'`.
140
141The character encodings currently supported by Node.js are the following:
142
143* `'utf8'` (alias: `'utf-8'`): Multi-byte encoded Unicode characters. Many web
144  pages and other document formats use [UTF-8][]. This is the default character
145  encoding. When decoding a `Buffer` into a string that does not exclusively
146  contain valid UTF-8 data, the Unicode replacement character `U+FFFD` � will be
147  used to represent those errors.
148
149* `'utf16le'` (alias: `'utf-16le'`): Multi-byte encoded Unicode characters.
150  Unlike `'utf8'`, each character in the string will be encoded using either 2
151  or 4 bytes. Node.js only supports the [little-endian][endianness] variant of
152  [UTF-16][].
153
154* `'latin1'`: Latin-1 stands for [ISO-8859-1][]. This character encoding only
155  supports the Unicode characters from `U+0000` to `U+00FF`. Each character is
156  encoded using a single byte. Characters that do not fit into that range are
157  truncated and will be mapped to characters in that range.
158
159Converting a `Buffer` into a string using one of the above is referred to as
160decoding, and converting a string into a `Buffer` is referred to as encoding.
161
162Node.js also supports the following binary-to-text encodings. For
163binary-to-text encodings, the naming convention is reversed: Converting a
164`Buffer` into a string is typically referred to as encoding, and converting a
165string into a `Buffer` as decoding.
166
167* `'base64'`: [Base64][] encoding. When creating a `Buffer` from a string,
168  this encoding will also correctly accept "URL and Filename Safe Alphabet" as
169  specified in [RFC 4648, Section 5][]. Whitespace characters such as spaces,
170  tabs, and new lines contained within the base64-encoded string are ignored.
171
172* `'base64url'`: [base64url][] encoding as specified in
173  [RFC 4648, Section 5][]. When creating a `Buffer` from a string, this
174  encoding will also correctly accept regular base64-encoded strings. When
175  encoding a `Buffer` to a string, this encoding will omit padding.
176
177* `'hex'`: Encode each byte as two hexadecimal characters. Data truncation
178  may occur when decoding strings that do not exclusively consist of an even
179  number of hexadecimal characters. See below for an example.
180
181The following legacy character encodings are also supported:
182
183* `'ascii'`: For 7-bit [ASCII][] data only. When encoding a string into a
184  `Buffer`, this is equivalent to using `'latin1'`. When decoding a `Buffer`
185  into a string, using this encoding will additionally unset the highest bit of
186  each byte before decoding as `'latin1'`.
187  Generally, there should be no reason to use this encoding, as `'utf8'`
188  (or, if the data is known to always be ASCII-only, `'latin1'`) will be a
189  better choice when encoding or decoding ASCII-only text. It is only provided
190  for legacy compatibility.
191
192* `'binary'`: Alias for `'latin1'`.
193  The name of this encoding can be very misleading, as all of the
194  encodings listed here convert between strings and binary data. For converting
195  between strings and `Buffer`s, typically `'utf8'` is the right choice.
196
197* `'ucs2'`, `'ucs-2'`: Aliases of `'utf16le'`. UCS-2 used to refer to a variant
198  of UTF-16 that did not support characters that had code points larger than
199  U+FFFF. In Node.js, these code points are always supported.
200
201```mjs
202import { Buffer } from 'node:buffer';
203
204Buffer.from('1ag123', 'hex');
205// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
206// ('g') encountered.
207
208Buffer.from('1a7', 'hex');
209// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').
210
211Buffer.from('1634', 'hex');
212// Prints <Buffer 16 34>, all data represented.
213```
214
215```cjs
216const { Buffer } = require('node:buffer');
217
218Buffer.from('1ag123', 'hex');
219// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
220// ('g') encountered.
221
222Buffer.from('1a7', 'hex');
223// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').
224
225Buffer.from('1634', 'hex');
226// Prints <Buffer 16 34>, all data represented.
227```
228
229Modern Web browsers follow the [WHATWG Encoding Standard][] which aliases
230both `'latin1'` and `'ISO-8859-1'` to `'win-1252'`. This means that while doing
231something like `http.get()`, if the returned charset is one of those listed in
232the WHATWG specification it is possible that the server actually returned
233`'win-1252'`-encoded data, and using `'latin1'` encoding may incorrectly decode
234the characters.
235
236## Buffers and TypedArrays
237
238<!-- YAML
239changes:
240  - version: v3.0.0
241    pr-url: https://github.com/nodejs/node/pull/2002
242    description: The `Buffer`s class now inherits from `Uint8Array`.
243-->
244
245`Buffer` instances are also JavaScript [`Uint8Array`][] and [`TypedArray`][]
246instances. All [`TypedArray`][] methods are available on `Buffer`s. There are,
247however, subtle incompatibilities between the `Buffer` API and the
248[`TypedArray`][] API.
249
250In particular:
251
252* While [`TypedArray.prototype.slice()`][] creates a copy of part of the `TypedArray`,
253  [`Buffer.prototype.slice()`][`buf.slice()`] creates a view over the existing `Buffer`
254  without copying. This behavior can be surprising, and only exists for legacy
255  compatibility. [`TypedArray.prototype.subarray()`][] can be used to achieve
256  the behavior of [`Buffer.prototype.slice()`][`buf.slice()`] on both `Buffer`s
257  and other `TypedArray`s and should be preferred.
258* [`buf.toString()`][] is incompatible with its `TypedArray` equivalent.
259* A number of methods, e.g. [`buf.indexOf()`][], support additional arguments.
260
261There are two ways to create new [`TypedArray`][] instances from a `Buffer`:
262
263* Passing a `Buffer` to a [`TypedArray`][] constructor will copy the `Buffer`s
264  contents, interpreted as an array of integers, and not as a byte sequence
265  of the target type.
266
267```mjs
268import { Buffer } from 'node:buffer';
269
270const buf = Buffer.from([1, 2, 3, 4]);
271const uint32array = new Uint32Array(buf);
272
273console.log(uint32array);
274
275// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
276```
277
278```cjs
279const { Buffer } = require('node:buffer');
280
281const buf = Buffer.from([1, 2, 3, 4]);
282const uint32array = new Uint32Array(buf);
283
284console.log(uint32array);
285
286// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
287```
288
289* Passing the `Buffer`s underlying [`ArrayBuffer`][] will create a
290  [`TypedArray`][] that shares its memory with the `Buffer`.
291
292```mjs
293import { Buffer } from 'node:buffer';
294
295const buf = Buffer.from('hello', 'utf16le');
296const uint16array = new Uint16Array(
297  buf.buffer,
298  buf.byteOffset,
299  buf.length / Uint16Array.BYTES_PER_ELEMENT);
300
301console.log(uint16array);
302
303// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
304```
305
306```cjs
307const { Buffer } = require('node:buffer');
308
309const buf = Buffer.from('hello', 'utf16le');
310const uint16array = new Uint16Array(
311  buf.buffer,
312  buf.byteOffset,
313  buf.length / Uint16Array.BYTES_PER_ELEMENT);
314
315console.log(uint16array);
316
317// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
318```
319
320It is possible to create a new `Buffer` that shares the same allocated
321memory as a [`TypedArray`][] instance by using the `TypedArray` object's
322`.buffer` property in the same way. [`Buffer.from()`][`Buffer.from(arrayBuf)`]
323behaves like `new Uint8Array()` in this context.
324
325```mjs
326import { Buffer } from 'node:buffer';
327
328const arr = new Uint16Array(2);
329
330arr[0] = 5000;
331arr[1] = 4000;
332
333// Copies the contents of `arr`.
334const buf1 = Buffer.from(arr);
335
336// Shares memory with `arr`.
337const buf2 = Buffer.from(arr.buffer);
338
339console.log(buf1);
340// Prints: <Buffer 88 a0>
341console.log(buf2);
342// Prints: <Buffer 88 13 a0 0f>
343
344arr[1] = 6000;
345
346console.log(buf1);
347// Prints: <Buffer 88 a0>
348console.log(buf2);
349// Prints: <Buffer 88 13 70 17>
350```
351
352```cjs
353const { Buffer } = require('node:buffer');
354
355const arr = new Uint16Array(2);
356
357arr[0] = 5000;
358arr[1] = 4000;
359
360// Copies the contents of `arr`.
361const buf1 = Buffer.from(arr);
362
363// Shares memory with `arr`.
364const buf2 = Buffer.from(arr.buffer);
365
366console.log(buf1);
367// Prints: <Buffer 88 a0>
368console.log(buf2);
369// Prints: <Buffer 88 13 a0 0f>
370
371arr[1] = 6000;
372
373console.log(buf1);
374// Prints: <Buffer 88 a0>
375console.log(buf2);
376// Prints: <Buffer 88 13 70 17>
377```
378
379When creating a `Buffer` using a [`TypedArray`][]'s `.buffer`, it is
380possible to use only a portion of the underlying [`ArrayBuffer`][] by passing in
381`byteOffset` and `length` parameters.
382
383```mjs
384import { Buffer } from 'node:buffer';
385
386const arr = new Uint16Array(20);
387const buf = Buffer.from(arr.buffer, 0, 16);
388
389console.log(buf.length);
390// Prints: 16
391```
392
393```cjs
394const { Buffer } = require('node:buffer');
395
396const arr = new Uint16Array(20);
397const buf = Buffer.from(arr.buffer, 0, 16);
398
399console.log(buf.length);
400// Prints: 16
401```
402
403The `Buffer.from()` and [`TypedArray.from()`][] have different signatures and
404implementations. Specifically, the [`TypedArray`][] variants accept a second
405argument that is a mapping function that is invoked on every element of the
406typed array:
407
408* `TypedArray.from(source[, mapFn[, thisArg]])`
409
410The `Buffer.from()` method, however, does not support the use of a mapping
411function:
412
413* [`Buffer.from(array)`][]
414* [`Buffer.from(buffer)`][]
415* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
416* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`]
417
418## Buffers and iteration
419
420`Buffer` instances can be iterated over using `for..of` syntax:
421
422```mjs
423import { Buffer } from 'node:buffer';
424
425const buf = Buffer.from([1, 2, 3]);
426
427for (const b of buf) {
428  console.log(b);
429}
430// Prints:
431//   1
432//   2
433//   3
434```
435
436```cjs
437const { Buffer } = require('node:buffer');
438
439const buf = Buffer.from([1, 2, 3]);
440
441for (const b of buf) {
442  console.log(b);
443}
444// Prints:
445//   1
446//   2
447//   3
448```
449
450Additionally, the [`buf.values()`][], [`buf.keys()`][], and
451[`buf.entries()`][] methods can be used to create iterators.
452
453## Class: `Blob`
454
455<!-- YAML
456added:
457  - v15.7.0
458  - v14.18.0
459changes:
460  - version: v18.0.0
461    pr-url: https://github.com/nodejs/node/pull/41270
462    description: No longer experimental.
463-->
464
465A [`Blob`][] encapsulates immutable, raw data that can be safely shared across
466multiple worker threads.
467
468### `new buffer.Blob([sources[, options]])`
469
470<!-- YAML
471added:
472  - v15.7.0
473  - v14.18.0
474changes:
475  - version: v16.7.0
476    pr-url: https://github.com/nodejs/node/pull/39708
477    description: Added the standard `endings` option to replace line-endings,
478                 and removed the non-standard `encoding` option.
479-->
480
481* `sources` {string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[]} An
482  array of string, {ArrayBuffer}, {TypedArray}, {DataView}, or {Blob} objects,
483  or any mix of such objects, that will be stored within the `Blob`.
484* `options` {Object}
485  * `endings` {string} One of either `'transparent'` or `'native'`. When set
486    to `'native'`, line endings in string source parts will be converted to
487    the platform native line-ending as specified by `require('node:os').EOL`.
488  * `type` {string} The Blob content-type. The intent is for `type` to convey
489    the MIME media type of the data, however no validation of the type format
490    is performed.
491
492Creates a new `Blob` object containing a concatenation of the given sources.
493
494{ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into
495the 'Blob' and can therefore be safely modified after the 'Blob' is created.
496
497String sources are encoded as UTF-8 byte sequences and copied into the Blob.
498Unmatched surrogate pairs within each string part will be replaced by Unicode
499U+FFFD replacement characters.
500
501### `blob.arrayBuffer()`
502
503<!-- YAML
504added:
505  - v15.7.0
506  - v14.18.0
507-->
508
509* Returns: {Promise}
510
511Returns a promise that fulfills with an {ArrayBuffer} containing a copy of
512the `Blob` data.
513
514### `blob.size`
515
516<!-- YAML
517added:
518  - v15.7.0
519  - v14.18.0
520-->
521
522The total size of the `Blob` in bytes.
523
524### `blob.slice([start[, end[, type]]])`
525
526<!-- YAML
527added:
528  - v15.7.0
529  - v14.18.0
530-->
531
532* `start` {number} The starting index.
533* `end` {number} The ending index.
534* `type` {string} The content-type for the new `Blob`
535
536Creates and returns a new `Blob` containing a subset of this `Blob` objects
537data. The original `Blob` is not altered.
538
539### `blob.stream()`
540
541<!-- YAML
542added: v16.7.0
543-->
544
545* Returns: {ReadableStream}
546
547Returns a new `ReadableStream` that allows the content of the `Blob` to be read.
548
549### `blob.text()`
550
551<!-- YAML
552added:
553  - v15.7.0
554  - v14.18.0
555-->
556
557* Returns: {Promise}
558
559Returns a promise that fulfills with the contents of the `Blob` decoded as a
560UTF-8 string.
561
562### `blob.type`
563
564<!-- YAML
565added:
566  - v15.7.0
567  - v14.18.0
568-->
569
570* Type: {string}
571
572The content-type of the `Blob`.
573
574### `Blob` objects and `MessageChannel`
575
576Once a {Blob} object is created, it can be sent via `MessagePort` to multiple
577destinations without transferring or immediately copying the data. The data
578contained by the `Blob` is copied only when the `arrayBuffer()` or `text()`
579methods are called.
580
581```mjs
582import { Blob } from 'node:buffer';
583import { setTimeout as delay } from 'node:timers/promises';
584
585const blob = new Blob(['hello there']);
586
587const mc1 = new MessageChannel();
588const mc2 = new MessageChannel();
589
590mc1.port1.onmessage = async ({ data }) => {
591  console.log(await data.arrayBuffer());
592  mc1.port1.close();
593};
594
595mc2.port1.onmessage = async ({ data }) => {
596  await delay(1000);
597  console.log(await data.arrayBuffer());
598  mc2.port1.close();
599};
600
601mc1.port2.postMessage(blob);
602mc2.port2.postMessage(blob);
603
604// The Blob is still usable after posting.
605blob.text().then(console.log);
606```
607
608```cjs
609const { Blob } = require('node:buffer');
610const { setTimeout: delay } = require('node:timers/promises');
611
612const blob = new Blob(['hello there']);
613
614const mc1 = new MessageChannel();
615const mc2 = new MessageChannel();
616
617mc1.port1.onmessage = async ({ data }) => {
618  console.log(await data.arrayBuffer());
619  mc1.port1.close();
620};
621
622mc2.port1.onmessage = async ({ data }) => {
623  await delay(1000);
624  console.log(await data.arrayBuffer());
625  mc2.port1.close();
626};
627
628mc1.port2.postMessage(blob);
629mc2.port2.postMessage(blob);
630
631// The Blob is still usable after posting.
632blob.text().then(console.log);
633```
634
635## Class: `Buffer`
636
637The `Buffer` class is a global type for dealing with binary data directly.
638It can be constructed in a variety of ways.
639
640### Static method: `Buffer.alloc(size[, fill[, encoding]])`
641
642<!-- YAML
643added: v5.10.0
644changes:
645  - version: v20.0.0
646    pr-url: https://github.com/nodejs/node/pull/45796
647    description: Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of
648                 ERR_INVALID_ARG_VALUE for invalid input arguments.
649  - version: v15.0.0
650    pr-url: https://github.com/nodejs/node/pull/34682
651    description: Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE
652                 for invalid input arguments.
653  - version: v10.0.0
654    pr-url: https://github.com/nodejs/node/pull/18129
655    description: Attempting to fill a non-zero length buffer with a zero length
656                 buffer triggers a thrown exception.
657  - version: v10.0.0
658    pr-url: https://github.com/nodejs/node/pull/17427
659    description: Specifying an invalid string for `fill` triggers a thrown
660                 exception.
661  - version: v8.9.3
662    pr-url: https://github.com/nodejs/node/pull/17428
663    description: Specifying an invalid string for `fill` now results in a
664                 zero-filled buffer.
665-->
666
667* `size` {integer} The desired length of the new `Buffer`.
668* `fill` {string|Buffer|Uint8Array|integer} A value to pre-fill the new `Buffer`
669  with. **Default:** `0`.
670* `encoding` {string} If `fill` is a string, this is its encoding.
671  **Default:** `'utf8'`.
672
673Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
674`Buffer` will be zero-filled.
675
676```mjs
677import { Buffer } from 'node:buffer';
678
679const buf = Buffer.alloc(5);
680
681console.log(buf);
682// Prints: <Buffer 00 00 00 00 00>
683```
684
685```cjs
686const { Buffer } = require('node:buffer');
687
688const buf = Buffer.alloc(5);
689
690console.log(buf);
691// Prints: <Buffer 00 00 00 00 00>
692```
693
694If `size` is larger than
695[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_OUT_OF_RANGE`][]
696is thrown.
697
698If `fill` is specified, the allocated `Buffer` will be initialized by calling
699[`buf.fill(fill)`][`buf.fill()`].
700
701```mjs
702import { Buffer } from 'node:buffer';
703
704const buf = Buffer.alloc(5, 'a');
705
706console.log(buf);
707// Prints: <Buffer 61 61 61 61 61>
708```
709
710```cjs
711const { Buffer } = require('node:buffer');
712
713const buf = Buffer.alloc(5, 'a');
714
715console.log(buf);
716// Prints: <Buffer 61 61 61 61 61>
717```
718
719If both `fill` and `encoding` are specified, the allocated `Buffer` will be
720initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`].
721
722```mjs
723import { Buffer } from 'node:buffer';
724
725const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
726
727console.log(buf);
728// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
729```
730
731```cjs
732const { Buffer } = require('node:buffer');
733
734const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
735
736console.log(buf);
737// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
738```
739
740Calling [`Buffer.alloc()`][] can be measurably slower than the alternative
741[`Buffer.allocUnsafe()`][] but ensures that the newly created `Buffer` instance
742contents will never contain sensitive data from previous allocations, including
743data that might not have been allocated for `Buffer`s.
744
745A `TypeError` will be thrown if `size` is not a number.
746
747### Static method: `Buffer.allocUnsafe(size)`
748
749<!-- YAML
750added: v5.10.0
751changes:
752  - version: v20.0.0
753    pr-url: https://github.com/nodejs/node/pull/45796
754    description: Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of
755                 ERR_INVALID_ARG_VALUE for invalid input arguments.
756  - version: v15.0.0
757    pr-url: https://github.com/nodejs/node/pull/34682
758    description: Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE
759                 for invalid input arguments.
760  - version: v7.0.0
761    pr-url: https://github.com/nodejs/node/pull/7079
762    description: Passing a negative `size` will now throw an error.
763-->
764
765* `size` {integer} The desired length of the new `Buffer`.
766
767Allocates a new `Buffer` of `size` bytes. If `size` is larger than
768[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_OUT_OF_RANGE`][]
769is thrown.
770
771The underlying memory for `Buffer` instances created in this way is _not
772initialized_. The contents of the newly created `Buffer` are unknown and
773_may contain sensitive data_. Use [`Buffer.alloc()`][] instead to initialize
774`Buffer` instances with zeroes.
775
776```mjs
777import { Buffer } from 'node:buffer';
778
779const buf = Buffer.allocUnsafe(10);
780
781console.log(buf);
782// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
783
784buf.fill(0);
785
786console.log(buf);
787// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
788```
789
790```cjs
791const { Buffer } = require('node:buffer');
792
793const buf = Buffer.allocUnsafe(10);
794
795console.log(buf);
796// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
797
798buf.fill(0);
799
800console.log(buf);
801// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
802```
803
804A `TypeError` will be thrown if `size` is not a number.
805
806The `Buffer` module pre-allocates an internal `Buffer` instance of
807size [`Buffer.poolSize`][] that is used as a pool for the fast allocation of new
808`Buffer` instances created using [`Buffer.allocUnsafe()`][], [`Buffer.from(array)`][],
809and [`Buffer.concat()`][] only when `size` is less than or equal to
810`Buffer.poolSize >> 1` (floor of [`Buffer.poolSize`][] divided by two).
811
812Use of this pre-allocated internal memory pool is a key difference between
813calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
814Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`
815pool, while `Buffer.allocUnsafe(size).fill(fill)` _will_ use the internal
816`Buffer` pool if `size` is less than or equal to half [`Buffer.poolSize`][]. The
817difference is subtle but can be important when an application requires the
818additional performance that [`Buffer.allocUnsafe()`][] provides.
819
820### Static method: `Buffer.allocUnsafeSlow(size)`
821
822<!-- YAML
823added: v5.12.0
824changes:
825  - version: v20.0.0
826    pr-url: https://github.com/nodejs/node/pull/45796
827    description: Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of
828                 ERR_INVALID_ARG_VALUE for invalid input arguments.
829  - version: v15.0.0
830    pr-url: https://github.com/nodejs/node/pull/34682
831    description: Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE
832                 for invalid input arguments.
833-->
834
835* `size` {integer} The desired length of the new `Buffer`.
836
837Allocates a new `Buffer` of `size` bytes. If `size` is larger than
838[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_OUT_OF_RANGE`][]
839is thrown. A zero-length `Buffer` is created if `size` is 0.
840
841The underlying memory for `Buffer` instances created in this way is _not
842initialized_. The contents of the newly created `Buffer` are unknown and
843_may contain sensitive data_. Use [`buf.fill(0)`][`buf.fill()`] to initialize
844such `Buffer` instances with zeroes.
845
846When using [`Buffer.allocUnsafe()`][] to allocate new `Buffer` instances,
847allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This
848allows applications to avoid the garbage collection overhead of creating many
849individually allocated `Buffer` instances. This approach improves both
850performance and memory usage by eliminating the need to track and clean up as
851many individual `ArrayBuffer` objects.
852
853However, in the case where a developer may need to retain a small chunk of
854memory from a pool for an indeterminate amount of time, it may be appropriate
855to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and
856then copying out the relevant bits.
857
858```mjs
859import { Buffer } from 'node:buffer';
860
861// Need to keep around a few small chunks of memory.
862const store = [];
863
864socket.on('readable', () => {
865  let data;
866  while (null !== (data = readable.read())) {
867    // Allocate for retained data.
868    const sb = Buffer.allocUnsafeSlow(10);
869
870    // Copy the data into the new allocation.
871    data.copy(sb, 0, 0, 10);
872
873    store.push(sb);
874  }
875});
876```
877
878```cjs
879const { Buffer } = require('node:buffer');
880
881// Need to keep around a few small chunks of memory.
882const store = [];
883
884socket.on('readable', () => {
885  let data;
886  while (null !== (data = readable.read())) {
887    // Allocate for retained data.
888    const sb = Buffer.allocUnsafeSlow(10);
889
890    // Copy the data into the new allocation.
891    data.copy(sb, 0, 0, 10);
892
893    store.push(sb);
894  }
895});
896```
897
898A `TypeError` will be thrown if `size` is not a number.
899
900### Static method: `Buffer.byteLength(string[, encoding])`
901
902<!-- YAML
903added: v0.1.90
904changes:
905  - version: v7.0.0
906    pr-url: https://github.com/nodejs/node/pull/8946
907    description: Passing invalid input will now throw an error.
908  - version: v5.10.0
909    pr-url: https://github.com/nodejs/node/pull/5255
910    description: The `string` parameter can now be any `TypedArray`, `DataView`
911                 or `ArrayBuffer`.
912-->
913
914* `string` {string|Buffer|TypedArray|DataView|ArrayBuffer|SharedArrayBuffer} A
915  value to calculate the length of.
916* `encoding` {string} If `string` is a string, this is its encoding.
917  **Default:** `'utf8'`.
918* Returns: {integer} The number of bytes contained within `string`.
919
920Returns the byte length of a string when encoded using `encoding`.
921This is not the same as [`String.prototype.length`][], which does not account
922for the encoding that is used to convert the string into bytes.
923
924For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input.
925For strings that contain non-base64/hex-encoded data (e.g. whitespace), the
926return value might be greater than the length of a `Buffer` created from the
927string.
928
929```mjs
930import { Buffer } from 'node:buffer';
931
932const str = '\u00bd + \u00bc = \u00be';
933
934console.log(`${str}: ${str.length} characters, ` +
935            `${Buffer.byteLength(str, 'utf8')} bytes`);
936// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
937```
938
939```cjs
940const { Buffer } = require('node:buffer');
941
942const str = '\u00bd + \u00bc = \u00be';
943
944console.log(`${str}: ${str.length} characters, ` +
945            `${Buffer.byteLength(str, 'utf8')} bytes`);
946// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
947```
948
949When `string` is a `Buffer`/[`DataView`][]/[`TypedArray`][]/[`ArrayBuffer`][]/
950[`SharedArrayBuffer`][], the byte length as reported by `.byteLength`
951is returned.
952
953### Static method: `Buffer.compare(buf1, buf2)`
954
955<!-- YAML
956added: v0.11.13
957changes:
958  - version: v8.0.0
959    pr-url: https://github.com/nodejs/node/pull/10236
960    description: The arguments can now be `Uint8Array`s.
961-->
962
963* `buf1` {Buffer|Uint8Array}
964* `buf2` {Buffer|Uint8Array}
965* Returns: {integer} Either `-1`, `0`, or `1`, depending on the result of the
966  comparison. See [`buf.compare()`][] for details.
967
968Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of
969`Buffer` instances. This is equivalent to calling
970[`buf1.compare(buf2)`][`buf.compare()`].
971
972```mjs
973import { Buffer } from 'node:buffer';
974
975const buf1 = Buffer.from('1234');
976const buf2 = Buffer.from('0123');
977const arr = [buf1, buf2];
978
979console.log(arr.sort(Buffer.compare));
980// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
981// (This result is equal to: [buf2, buf1].)
982```
983
984```cjs
985const { Buffer } = require('node:buffer');
986
987const buf1 = Buffer.from('1234');
988const buf2 = Buffer.from('0123');
989const arr = [buf1, buf2];
990
991console.log(arr.sort(Buffer.compare));
992// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
993// (This result is equal to: [buf2, buf1].)
994```
995
996### Static method: `Buffer.concat(list[, totalLength])`
997
998<!-- YAML
999added: v0.7.11
1000changes:
1001  - version: v8.0.0
1002    pr-url: https://github.com/nodejs/node/pull/10236
1003    description: The elements of `list` can now be `Uint8Array`s.
1004-->
1005
1006* `list` {Buffer\[] | Uint8Array\[]} List of `Buffer` or [`Uint8Array`][]
1007  instances to concatenate.
1008* `totalLength` {integer} Total length of the `Buffer` instances in `list`
1009  when concatenated.
1010* Returns: {Buffer}
1011
1012Returns a new `Buffer` which is the result of concatenating all the `Buffer`
1013instances in the `list` together.
1014
1015If the list has no items, or if the `totalLength` is 0, then a new zero-length
1016`Buffer` is returned.
1017
1018If `totalLength` is not provided, it is calculated from the `Buffer` instances
1019in `list` by adding their lengths.
1020
1021If `totalLength` is provided, it is coerced to an unsigned integer. If the
1022combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
1023truncated to `totalLength`.
1024
1025```mjs
1026import { Buffer } from 'node:buffer';
1027
1028// Create a single `Buffer` from a list of three `Buffer` instances.
1029
1030const buf1 = Buffer.alloc(10);
1031const buf2 = Buffer.alloc(14);
1032const buf3 = Buffer.alloc(18);
1033const totalLength = buf1.length + buf2.length + buf3.length;
1034
1035console.log(totalLength);
1036// Prints: 42
1037
1038const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
1039
1040console.log(bufA);
1041// Prints: <Buffer 00 00 00 00 ...>
1042console.log(bufA.length);
1043// Prints: 42
1044```
1045
1046```cjs
1047const { Buffer } = require('node:buffer');
1048
1049// Create a single `Buffer` from a list of three `Buffer` instances.
1050
1051const buf1 = Buffer.alloc(10);
1052const buf2 = Buffer.alloc(14);
1053const buf3 = Buffer.alloc(18);
1054const totalLength = buf1.length + buf2.length + buf3.length;
1055
1056console.log(totalLength);
1057// Prints: 42
1058
1059const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
1060
1061console.log(bufA);
1062// Prints: <Buffer 00 00 00 00 ...>
1063console.log(bufA.length);
1064// Prints: 42
1065```
1066
1067`Buffer.concat()` may also use the internal `Buffer` pool like
1068[`Buffer.allocUnsafe()`][] does.
1069
1070### Static method: `Buffer.copyBytesFrom(view[, offset[, length]])`
1071
1072<!-- YAML
1073added: v18.16.0
1074-->
1075
1076* `view` {TypedArray} The {TypedArray} to copy.
1077* `offset` {integer} The starting offset within `view`. **Default:**: `0`.
1078* `length` {integer} The number of elements from `view` to copy.
1079  **Default:** `view.length - offset`.
1080
1081Copies the underlying memory of `view` into a new `Buffer`.
1082
1083```js
1084const u16 = new Uint16Array([0, 0xffff]);
1085const buf = Buffer.copyBytesFrom(u16, 1, 1);
1086u16[1] = 0;
1087console.log(buf.length); // 2
1088console.log(buf[0]); // 255
1089console.log(buf[1]); // 255
1090```
1091
1092### Static method: `Buffer.from(array)`
1093
1094<!-- YAML
1095added: v5.10.0
1096-->
1097
1098* `array` {integer\[]}
1099
1100Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`.
1101Array entries outside that range will be truncated to fit into it.
1102
1103```mjs
1104import { Buffer } from 'node:buffer';
1105
1106// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
1107const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
1108```
1109
1110```cjs
1111const { Buffer } = require('node:buffer');
1112
1113// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
1114const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
1115```
1116
1117If `array` is an `Array`-like object (that is, one with a `length` property of
1118type `number`), it is treated as if it is an array, unless it is a `Buffer` or
1119a `Uint8Array`. This means all other `TypedArray` variants get treated as an
1120`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use
1121[`Buffer.copyBytesFrom()`][].
1122
1123A `TypeError` will be thrown if `array` is not an `Array` or another type
1124appropriate for `Buffer.from()` variants.
1125
1126`Buffer.from(array)` and [`Buffer.from(string)`][] may also use the internal
1127`Buffer` pool like [`Buffer.allocUnsafe()`][] does.
1128
1129### Static method: `Buffer.from(arrayBuffer[, byteOffset[, length]])`
1130
1131<!-- YAML
1132added: v5.10.0
1133-->
1134
1135* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][],
1136  [`SharedArrayBuffer`][], for example the `.buffer` property of a
1137  [`TypedArray`][].
1138* `byteOffset` {integer} Index of first byte to expose. **Default:** `0`.
1139* `length` {integer} Number of bytes to expose.
1140  **Default:** `arrayBuffer.byteLength - byteOffset`.
1141
1142This creates a view of the [`ArrayBuffer`][] without copying the underlying
1143memory. For example, when passed a reference to the `.buffer` property of a
1144[`TypedArray`][] instance, the newly created `Buffer` will share the same
1145allocated memory as the [`TypedArray`][]'s underlying `ArrayBuffer`.
1146
1147```mjs
1148import { Buffer } from 'node:buffer';
1149
1150const arr = new Uint16Array(2);
1151
1152arr[0] = 5000;
1153arr[1] = 4000;
1154
1155// Shares memory with `arr`.
1156const buf = Buffer.from(arr.buffer);
1157
1158console.log(buf);
1159// Prints: <Buffer 88 13 a0 0f>
1160
1161// Changing the original Uint16Array changes the Buffer also.
1162arr[1] = 6000;
1163
1164console.log(buf);
1165// Prints: <Buffer 88 13 70 17>
1166```
1167
1168```cjs
1169const { Buffer } = require('node:buffer');
1170
1171const arr = new Uint16Array(2);
1172
1173arr[0] = 5000;
1174arr[1] = 4000;
1175
1176// Shares memory with `arr`.
1177const buf = Buffer.from(arr.buffer);
1178
1179console.log(buf);
1180// Prints: <Buffer 88 13 a0 0f>
1181
1182// Changing the original Uint16Array changes the Buffer also.
1183arr[1] = 6000;
1184
1185console.log(buf);
1186// Prints: <Buffer 88 13 70 17>
1187```
1188
1189The optional `byteOffset` and `length` arguments specify a memory range within
1190the `arrayBuffer` that will be shared by the `Buffer`.
1191
1192```mjs
1193import { Buffer } from 'node:buffer';
1194
1195const ab = new ArrayBuffer(10);
1196const buf = Buffer.from(ab, 0, 2);
1197
1198console.log(buf.length);
1199// Prints: 2
1200```
1201
1202```cjs
1203const { Buffer } = require('node:buffer');
1204
1205const ab = new ArrayBuffer(10);
1206const buf = Buffer.from(ab, 0, 2);
1207
1208console.log(buf.length);
1209// Prints: 2
1210```
1211
1212A `TypeError` will be thrown if `arrayBuffer` is not an [`ArrayBuffer`][] or a
1213[`SharedArrayBuffer`][] or another type appropriate for `Buffer.from()`
1214variants.
1215
1216It is important to remember that a backing `ArrayBuffer` can cover a range
1217of memory that extends beyond the bounds of a `TypedArray` view. A new
1218`Buffer` created using the `buffer` property of a `TypedArray` may extend
1219beyond the range of the `TypedArray`:
1220
1221```mjs
1222import { Buffer } from 'node:buffer';
1223
1224const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
1225const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
1226console.log(arrA.buffer === arrB.buffer); // true
1227
1228const buf = Buffer.from(arrB.buffer);
1229console.log(buf);
1230// Prints: <Buffer 63 64 65 66>
1231```
1232
1233```cjs
1234const { Buffer } = require('node:buffer');
1235
1236const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
1237const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
1238console.log(arrA.buffer === arrB.buffer); // true
1239
1240const buf = Buffer.from(arrB.buffer);
1241console.log(buf);
1242// Prints: <Buffer 63 64 65 66>
1243```
1244
1245### Static method: `Buffer.from(buffer)`
1246
1247<!-- YAML
1248added: v5.10.0
1249-->
1250
1251* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from
1252  which to copy data.
1253
1254Copies the passed `buffer` data onto a new `Buffer` instance.
1255
1256```mjs
1257import { Buffer } from 'node:buffer';
1258
1259const buf1 = Buffer.from('buffer');
1260const buf2 = Buffer.from(buf1);
1261
1262buf1[0] = 0x61;
1263
1264console.log(buf1.toString());
1265// Prints: auffer
1266console.log(buf2.toString());
1267// Prints: buffer
1268```
1269
1270```cjs
1271const { Buffer } = require('node:buffer');
1272
1273const buf1 = Buffer.from('buffer');
1274const buf2 = Buffer.from(buf1);
1275
1276buf1[0] = 0x61;
1277
1278console.log(buf1.toString());
1279// Prints: auffer
1280console.log(buf2.toString());
1281// Prints: buffer
1282```
1283
1284A `TypeError` will be thrown if `buffer` is not a `Buffer` or another type
1285appropriate for `Buffer.from()` variants.
1286
1287### Static method: `Buffer.from(object[, offsetOrEncoding[, length]])`
1288
1289<!-- YAML
1290added: v8.2.0
1291-->
1292
1293* `object` {Object} An object supporting `Symbol.toPrimitive` or `valueOf()`.
1294* `offsetOrEncoding` {integer|string} A byte-offset or encoding.
1295* `length` {integer} A length.
1296
1297For objects whose `valueOf()` function returns a value not strictly equal to
1298`object`, returns `Buffer.from(object.valueOf(), offsetOrEncoding, length)`.
1299
1300```mjs
1301import { Buffer } from 'node:buffer';
1302
1303const buf = Buffer.from(new String('this is a test'));
1304// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
1305```
1306
1307```cjs
1308const { Buffer } = require('node:buffer');
1309
1310const buf = Buffer.from(new String('this is a test'));
1311// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
1312```
1313
1314For objects that support `Symbol.toPrimitive`, returns
1315`Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)`.
1316
1317```mjs
1318import { Buffer } from 'node:buffer';
1319
1320class Foo {
1321  [Symbol.toPrimitive]() {
1322    return 'this is a test';
1323  }
1324}
1325
1326const buf = Buffer.from(new Foo(), 'utf8');
1327// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
1328```
1329
1330```cjs
1331const { Buffer } = require('node:buffer');
1332
1333class Foo {
1334  [Symbol.toPrimitive]() {
1335    return 'this is a test';
1336  }
1337}
1338
1339const buf = Buffer.from(new Foo(), 'utf8');
1340// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
1341```
1342
1343A `TypeError` will be thrown if `object` does not have the mentioned methods or
1344is not of another type appropriate for `Buffer.from()` variants.
1345
1346### Static method: `Buffer.from(string[, encoding])`
1347
1348<!-- YAML
1349added: v5.10.0
1350-->
1351
1352* `string` {string} A string to encode.
1353* `encoding` {string} The encoding of `string`. **Default:** `'utf8'`.
1354
1355Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
1356the character encoding to be used when converting `string` into bytes.
1357
1358```mjs
1359import { Buffer } from 'node:buffer';
1360
1361const buf1 = Buffer.from('this is a tést');
1362const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
1363
1364console.log(buf1.toString());
1365// Prints: this is a tést
1366console.log(buf2.toString());
1367// Prints: this is a tést
1368console.log(buf1.toString('latin1'));
1369// Prints: this is a tést
1370```
1371
1372```cjs
1373const { Buffer } = require('node:buffer');
1374
1375const buf1 = Buffer.from('this is a tést');
1376const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
1377
1378console.log(buf1.toString());
1379// Prints: this is a tést
1380console.log(buf2.toString());
1381// Prints: this is a tést
1382console.log(buf1.toString('latin1'));
1383// Prints: this is a tést
1384```
1385
1386A `TypeError` will be thrown if `string` is not a string or another type
1387appropriate for `Buffer.from()` variants.
1388
1389### Static method: `Buffer.isBuffer(obj)`
1390
1391<!-- YAML
1392added: v0.1.101
1393-->
1394
1395* `obj` {Object}
1396* Returns: {boolean}
1397
1398Returns `true` if `obj` is a `Buffer`, `false` otherwise.
1399
1400```mjs
1401import { Buffer } from 'node:buffer';
1402
1403Buffer.isBuffer(Buffer.alloc(10)); // true
1404Buffer.isBuffer(Buffer.from('foo')); // true
1405Buffer.isBuffer('a string'); // false
1406Buffer.isBuffer([]); // false
1407Buffer.isBuffer(new Uint8Array(1024)); // false
1408```
1409
1410```cjs
1411const { Buffer } = require('node:buffer');
1412
1413Buffer.isBuffer(Buffer.alloc(10)); // true
1414Buffer.isBuffer(Buffer.from('foo')); // true
1415Buffer.isBuffer('a string'); // false
1416Buffer.isBuffer([]); // false
1417Buffer.isBuffer(new Uint8Array(1024)); // false
1418```
1419
1420### Static method: `Buffer.isEncoding(encoding)`
1421
1422<!-- YAML
1423added: v0.9.1
1424-->
1425
1426* `encoding` {string} A character encoding name to check.
1427* Returns: {boolean}
1428
1429Returns `true` if `encoding` is the name of a supported character encoding,
1430or `false` otherwise.
1431
1432```mjs
1433import { Buffer } from 'node:buffer';
1434
1435console.log(Buffer.isEncoding('utf8'));
1436// Prints: true
1437
1438console.log(Buffer.isEncoding('hex'));
1439// Prints: true
1440
1441console.log(Buffer.isEncoding('utf/8'));
1442// Prints: false
1443
1444console.log(Buffer.isEncoding(''));
1445// Prints: false
1446```
1447
1448```cjs
1449const { Buffer } = require('node:buffer');
1450
1451console.log(Buffer.isEncoding('utf8'));
1452// Prints: true
1453
1454console.log(Buffer.isEncoding('hex'));
1455// Prints: true
1456
1457console.log(Buffer.isEncoding('utf/8'));
1458// Prints: false
1459
1460console.log(Buffer.isEncoding(''));
1461// Prints: false
1462```
1463
1464### Class property: `Buffer.poolSize`
1465
1466<!-- YAML
1467added: v0.11.3
1468-->
1469
1470* {integer} **Default:** `8192`
1471
1472This is the size (in bytes) of pre-allocated internal `Buffer` instances used
1473for pooling. This value may be modified.
1474
1475### `buf[index]`
1476
1477* `index` {integer}
1478
1479The index operator `[index]` can be used to get and set the octet at position
1480`index` in `buf`. The values refer to individual bytes, so the legal value
1481range is between `0x00` and `0xFF` (hex) or `0` and `255` (decimal).
1482
1483This operator is inherited from `Uint8Array`, so its behavior on out-of-bounds
1484access is the same as `Uint8Array`. In other words, `buf[index]` returns
1485`undefined` when `index` is negative or greater or equal to `buf.length`, and
1486`buf[index] = value` does not modify the buffer if `index` is negative or
1487`>= buf.length`.
1488
1489```mjs
1490import { Buffer } from 'node:buffer';
1491
1492// Copy an ASCII string into a `Buffer` one byte at a time.
1493// (This only works for ASCII-only strings. In general, one should use
1494// `Buffer.from()` to perform this conversion.)
1495
1496const str = 'Node.js';
1497const buf = Buffer.allocUnsafe(str.length);
1498
1499for (let i = 0; i < str.length; i++) {
1500  buf[i] = str.charCodeAt(i);
1501}
1502
1503console.log(buf.toString('utf8'));
1504// Prints: Node.js
1505```
1506
1507```cjs
1508const { Buffer } = require('node:buffer');
1509
1510// Copy an ASCII string into a `Buffer` one byte at a time.
1511// (This only works for ASCII-only strings. In general, one should use
1512// `Buffer.from()` to perform this conversion.)
1513
1514const str = 'Node.js';
1515const buf = Buffer.allocUnsafe(str.length);
1516
1517for (let i = 0; i < str.length; i++) {
1518  buf[i] = str.charCodeAt(i);
1519}
1520
1521console.log(buf.toString('utf8'));
1522// Prints: Node.js
1523```
1524
1525### `buf.buffer`
1526
1527* {ArrayBuffer} The underlying `ArrayBuffer` object based on which this `Buffer`
1528  object is created.
1529
1530This `ArrayBuffer` is not guaranteed to correspond exactly to the original
1531`Buffer`. See the notes on `buf.byteOffset` for details.
1532
1533```mjs
1534import { Buffer } from 'node:buffer';
1535
1536const arrayBuffer = new ArrayBuffer(16);
1537const buffer = Buffer.from(arrayBuffer);
1538
1539console.log(buffer.buffer === arrayBuffer);
1540// Prints: true
1541```
1542
1543```cjs
1544const { Buffer } = require('node:buffer');
1545
1546const arrayBuffer = new ArrayBuffer(16);
1547const buffer = Buffer.from(arrayBuffer);
1548
1549console.log(buffer.buffer === arrayBuffer);
1550// Prints: true
1551```
1552
1553### `buf.byteOffset`
1554
1555* {integer} The `byteOffset` of the `Buffer`s underlying `ArrayBuffer` object.
1556
1557When setting `byteOffset` in `Buffer.from(ArrayBuffer, byteOffset, length)`,
1558or sometimes when allocating a `Buffer` smaller than `Buffer.poolSize`, the
1559buffer does not start from a zero offset on the underlying `ArrayBuffer`.
1560
1561This can cause problems when accessing the underlying `ArrayBuffer` directly
1562using `buf.buffer`, as other parts of the `ArrayBuffer` may be unrelated
1563to the `Buffer` object itself.
1564
1565A common issue when creating a `TypedArray` object that shares its memory with
1566a `Buffer` is that in this case one needs to specify the `byteOffset` correctly:
1567
1568```mjs
1569import { Buffer } from 'node:buffer';
1570
1571// Create a buffer smaller than `Buffer.poolSize`.
1572const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1573
1574// When casting the Node.js Buffer to an Int8Array, use the byteOffset
1575// to refer only to the part of `nodeBuffer.buffer` that contains the memory
1576// for `nodeBuffer`.
1577new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
1578```
1579
1580```cjs
1581const { Buffer } = require('node:buffer');
1582
1583// Create a buffer smaller than `Buffer.poolSize`.
1584const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1585
1586// When casting the Node.js Buffer to an Int8Array, use the byteOffset
1587// to refer only to the part of `nodeBuffer.buffer` that contains the memory
1588// for `nodeBuffer`.
1589new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
1590```
1591
1592### `buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])`
1593
1594<!-- YAML
1595added: v0.11.13
1596changes:
1597  - version: v8.0.0
1598    pr-url: https://github.com/nodejs/node/pull/10236
1599    description: The `target` parameter can now be a `Uint8Array`.
1600  - version: v5.11.0
1601    pr-url: https://github.com/nodejs/node/pull/5880
1602    description: Additional parameters for specifying offsets are supported now.
1603-->
1604
1605* `target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to
1606  compare `buf`.
1607* `targetStart` {integer} The offset within `target` at which to begin
1608  comparison. **Default:** `0`.
1609* `targetEnd` {integer} The offset within `target` at which to end comparison
1610  (not inclusive). **Default:** `target.length`.
1611* `sourceStart` {integer} The offset within `buf` at which to begin comparison.
1612  **Default:** `0`.
1613* `sourceEnd` {integer} The offset within `buf` at which to end comparison
1614  (not inclusive). **Default:** [`buf.length`][].
1615* Returns: {integer}
1616
1617Compares `buf` with `target` and returns a number indicating whether `buf`
1618comes before, after, or is the same as `target` in sort order.
1619Comparison is based on the actual sequence of bytes in each `Buffer`.
1620
1621* `0` is returned if `target` is the same as `buf`
1622* `1` is returned if `target` should come _before_ `buf` when sorted.
1623* `-1` is returned if `target` should come _after_ `buf` when sorted.
1624
1625```mjs
1626import { Buffer } from 'node:buffer';
1627
1628const buf1 = Buffer.from('ABC');
1629const buf2 = Buffer.from('BCD');
1630const buf3 = Buffer.from('ABCD');
1631
1632console.log(buf1.compare(buf1));
1633// Prints: 0
1634console.log(buf1.compare(buf2));
1635// Prints: -1
1636console.log(buf1.compare(buf3));
1637// Prints: -1
1638console.log(buf2.compare(buf1));
1639// Prints: 1
1640console.log(buf2.compare(buf3));
1641// Prints: 1
1642console.log([buf1, buf2, buf3].sort(Buffer.compare));
1643// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
1644// (This result is equal to: [buf1, buf3, buf2].)
1645```
1646
1647```cjs
1648const { Buffer } = require('node:buffer');
1649
1650const buf1 = Buffer.from('ABC');
1651const buf2 = Buffer.from('BCD');
1652const buf3 = Buffer.from('ABCD');
1653
1654console.log(buf1.compare(buf1));
1655// Prints: 0
1656console.log(buf1.compare(buf2));
1657// Prints: -1
1658console.log(buf1.compare(buf3));
1659// Prints: -1
1660console.log(buf2.compare(buf1));
1661// Prints: 1
1662console.log(buf2.compare(buf3));
1663// Prints: 1
1664console.log([buf1, buf2, buf3].sort(Buffer.compare));
1665// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
1666// (This result is equal to: [buf1, buf3, buf2].)
1667```
1668
1669The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`
1670arguments can be used to limit the comparison to specific ranges within `target`
1671and `buf` respectively.
1672
1673```mjs
1674import { Buffer } from 'node:buffer';
1675
1676const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
1677const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
1678
1679console.log(buf1.compare(buf2, 5, 9, 0, 4));
1680// Prints: 0
1681console.log(buf1.compare(buf2, 0, 6, 4));
1682// Prints: -1
1683console.log(buf1.compare(buf2, 5, 6, 5));
1684// Prints: 1
1685```
1686
1687```cjs
1688const { Buffer } = require('node:buffer');
1689
1690const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
1691const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
1692
1693console.log(buf1.compare(buf2, 5, 9, 0, 4));
1694// Prints: 0
1695console.log(buf1.compare(buf2, 0, 6, 4));
1696// Prints: -1
1697console.log(buf1.compare(buf2, 5, 6, 5));
1698// Prints: 1
1699```
1700
1701[`ERR_OUT_OF_RANGE`][] is thrown if `targetStart < 0`, `sourceStart < 0`,
1702`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`.
1703
1704### `buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])`
1705
1706<!-- YAML
1707added: v0.1.90
1708-->
1709
1710* `target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] to copy into.
1711* `targetStart` {integer} The offset within `target` at which to begin
1712  writing. **Default:** `0`.
1713* `sourceStart` {integer} The offset within `buf` from which to begin copying.
1714  **Default:** `0`.
1715* `sourceEnd` {integer} The offset within `buf` at which to stop copying (not
1716  inclusive). **Default:** [`buf.length`][].
1717* Returns: {integer} The number of bytes copied.
1718
1719Copies data from a region of `buf` to a region in `target`, even if the `target`
1720memory region overlaps with `buf`.
1721
1722[`TypedArray.prototype.set()`][] performs the same operation, and is available
1723for all TypedArrays, including Node.js `Buffer`s, although it takes
1724different function arguments.
1725
1726```mjs
1727import { Buffer } from 'node:buffer';
1728
1729// Create two `Buffer` instances.
1730const buf1 = Buffer.allocUnsafe(26);
1731const buf2 = Buffer.allocUnsafe(26).fill('!');
1732
1733for (let i = 0; i < 26; i++) {
1734  // 97 is the decimal ASCII value for 'a'.
1735  buf1[i] = i + 97;
1736}
1737
1738// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
1739buf1.copy(buf2, 8, 16, 20);
1740// This is equivalent to:
1741// buf2.set(buf1.subarray(16, 20), 8);
1742
1743console.log(buf2.toString('ascii', 0, 25));
1744// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
1745```
1746
1747```cjs
1748const { Buffer } = require('node:buffer');
1749
1750// Create two `Buffer` instances.
1751const buf1 = Buffer.allocUnsafe(26);
1752const buf2 = Buffer.allocUnsafe(26).fill('!');
1753
1754for (let i = 0; i < 26; i++) {
1755  // 97 is the decimal ASCII value for 'a'.
1756  buf1[i] = i + 97;
1757}
1758
1759// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
1760buf1.copy(buf2, 8, 16, 20);
1761// This is equivalent to:
1762// buf2.set(buf1.subarray(16, 20), 8);
1763
1764console.log(buf2.toString('ascii', 0, 25));
1765// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
1766```
1767
1768```mjs
1769import { Buffer } from 'node:buffer';
1770
1771// Create a `Buffer` and copy data from one region to an overlapping region
1772// within the same `Buffer`.
1773
1774const buf = Buffer.allocUnsafe(26);
1775
1776for (let i = 0; i < 26; i++) {
1777  // 97 is the decimal ASCII value for 'a'.
1778  buf[i] = i + 97;
1779}
1780
1781buf.copy(buf, 0, 4, 10);
1782
1783console.log(buf.toString());
1784// Prints: efghijghijklmnopqrstuvwxyz
1785```
1786
1787```cjs
1788const { Buffer } = require('node:buffer');
1789
1790// Create a `Buffer` and copy data from one region to an overlapping region
1791// within the same `Buffer`.
1792
1793const buf = Buffer.allocUnsafe(26);
1794
1795for (let i = 0; i < 26; i++) {
1796  // 97 is the decimal ASCII value for 'a'.
1797  buf[i] = i + 97;
1798}
1799
1800buf.copy(buf, 0, 4, 10);
1801
1802console.log(buf.toString());
1803// Prints: efghijghijklmnopqrstuvwxyz
1804```
1805
1806### `buf.entries()`
1807
1808<!-- YAML
1809added: v1.1.0
1810-->
1811
1812* Returns: {Iterator}
1813
1814Creates and returns an [iterator][] of `[index, byte]` pairs from the contents
1815of `buf`.
1816
1817```mjs
1818import { Buffer } from 'node:buffer';
1819
1820// Log the entire contents of a `Buffer`.
1821
1822const buf = Buffer.from('buffer');
1823
1824for (const pair of buf.entries()) {
1825  console.log(pair);
1826}
1827// Prints:
1828//   [0, 98]
1829//   [1, 117]
1830//   [2, 102]
1831//   [3, 102]
1832//   [4, 101]
1833//   [5, 114]
1834```
1835
1836```cjs
1837const { Buffer } = require('node:buffer');
1838
1839// Log the entire contents of a `Buffer`.
1840
1841const buf = Buffer.from('buffer');
1842
1843for (const pair of buf.entries()) {
1844  console.log(pair);
1845}
1846// Prints:
1847//   [0, 98]
1848//   [1, 117]
1849//   [2, 102]
1850//   [3, 102]
1851//   [4, 101]
1852//   [5, 114]
1853```
1854
1855### `buf.equals(otherBuffer)`
1856
1857<!-- YAML
1858added: v0.11.13
1859changes:
1860  - version: v8.0.0
1861    pr-url: https://github.com/nodejs/node/pull/10236
1862    description: The arguments can now be `Uint8Array`s.
1863-->
1864
1865* `otherBuffer` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to
1866  compare `buf`.
1867* Returns: {boolean}
1868
1869Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,
1870`false` otherwise. Equivalent to
1871[`buf.compare(otherBuffer) === 0`][`buf.compare()`].
1872
1873```mjs
1874import { Buffer } from 'node:buffer';
1875
1876const buf1 = Buffer.from('ABC');
1877const buf2 = Buffer.from('414243', 'hex');
1878const buf3 = Buffer.from('ABCD');
1879
1880console.log(buf1.equals(buf2));
1881// Prints: true
1882console.log(buf1.equals(buf3));
1883// Prints: false
1884```
1885
1886```cjs
1887const { Buffer } = require('node:buffer');
1888
1889const buf1 = Buffer.from('ABC');
1890const buf2 = Buffer.from('414243', 'hex');
1891const buf3 = Buffer.from('ABCD');
1892
1893console.log(buf1.equals(buf2));
1894// Prints: true
1895console.log(buf1.equals(buf3));
1896// Prints: false
1897```
1898
1899### `buf.fill(value[, offset[, end]][, encoding])`
1900
1901<!-- YAML
1902added: v0.5.0
1903changes:
1904  - version: v11.0.0
1905    pr-url: https://github.com/nodejs/node/pull/22969
1906    description: Throws `ERR_OUT_OF_RANGE` instead of `ERR_INDEX_OUT_OF_RANGE`.
1907  - version: v10.0.0
1908    pr-url: https://github.com/nodejs/node/pull/18790
1909    description: Negative `end` values throw an `ERR_INDEX_OUT_OF_RANGE` error.
1910  - version: v10.0.0
1911    pr-url: https://github.com/nodejs/node/pull/18129
1912    description: Attempting to fill a non-zero length buffer with a zero length
1913                 buffer triggers a thrown exception.
1914  - version: v10.0.0
1915    pr-url: https://github.com/nodejs/node/pull/17427
1916    description: Specifying an invalid string for `value` triggers a thrown
1917                 exception.
1918  - version: v5.7.0
1919    pr-url: https://github.com/nodejs/node/pull/4935
1920    description: The `encoding` parameter is supported now.
1921-->
1922
1923* `value` {string|Buffer|Uint8Array|integer} The value with which to fill `buf`.
1924  Empty value (string, Uint8Array, Buffer) is coerced to `0`.
1925* `offset` {integer} Number of bytes to skip before starting to fill `buf`.
1926  **Default:** `0`.
1927* `end` {integer} Where to stop filling `buf` (not inclusive). **Default:**
1928  [`buf.length`][].
1929* `encoding` {string} The encoding for `value` if `value` is a string.
1930  **Default:** `'utf8'`.
1931* Returns: {Buffer} A reference to `buf`.
1932
1933Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
1934the entire `buf` will be filled:
1935
1936```mjs
1937import { Buffer } from 'node:buffer';
1938
1939// Fill a `Buffer` with the ASCII character 'h'.
1940
1941const b = Buffer.allocUnsafe(50).fill('h');
1942
1943console.log(b.toString());
1944// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
1945
1946// Fill a buffer with empty string
1947const c = Buffer.allocUnsafe(5).fill('');
1948
1949console.log(c.fill(''));
1950// Prints: <Buffer 00 00 00 00 00>
1951```
1952
1953```cjs
1954const { Buffer } = require('node:buffer');
1955
1956// Fill a `Buffer` with the ASCII character 'h'.
1957
1958const b = Buffer.allocUnsafe(50).fill('h');
1959
1960console.log(b.toString());
1961// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
1962
1963// Fill a buffer with empty string
1964const c = Buffer.allocUnsafe(5).fill('');
1965
1966console.log(c.fill(''));
1967// Prints: <Buffer 00 00 00 00 00>
1968```
1969
1970`value` is coerced to a `uint32` value if it is not a string, `Buffer`, or
1971integer. If the resulting integer is greater than `255` (decimal), `buf` will be
1972filled with `value & 255`.
1973
1974If the final write of a `fill()` operation falls on a multi-byte character,
1975then only the bytes of that character that fit into `buf` are written:
1976
1977```mjs
1978import { Buffer } from 'node:buffer';
1979
1980// Fill a `Buffer` with character that takes up two bytes in UTF-8.
1981
1982console.log(Buffer.allocUnsafe(5).fill('\u0222'));
1983// Prints: <Buffer c8 a2 c8 a2 c8>
1984```
1985
1986```cjs
1987const { Buffer } = require('node:buffer');
1988
1989// Fill a `Buffer` with character that takes up two bytes in UTF-8.
1990
1991console.log(Buffer.allocUnsafe(5).fill('\u0222'));
1992// Prints: <Buffer c8 a2 c8 a2 c8>
1993```
1994
1995If `value` contains invalid characters, it is truncated; if no valid
1996fill data remains, an exception is thrown:
1997
1998```mjs
1999import { Buffer } from 'node:buffer';
2000
2001const buf = Buffer.allocUnsafe(5);
2002
2003console.log(buf.fill('a'));
2004// Prints: <Buffer 61 61 61 61 61>
2005console.log(buf.fill('aazz', 'hex'));
2006// Prints: <Buffer aa aa aa aa aa>
2007console.log(buf.fill('zz', 'hex'));
2008// Throws an exception.
2009```
2010
2011```cjs
2012const { Buffer } = require('node:buffer');
2013
2014const buf = Buffer.allocUnsafe(5);
2015
2016console.log(buf.fill('a'));
2017// Prints: <Buffer 61 61 61 61 61>
2018console.log(buf.fill('aazz', 'hex'));
2019// Prints: <Buffer aa aa aa aa aa>
2020console.log(buf.fill('zz', 'hex'));
2021// Throws an exception.
2022```
2023
2024### `buf.includes(value[, byteOffset][, encoding])`
2025
2026<!-- YAML
2027added: v5.3.0
2028-->
2029
2030* `value` {string|Buffer|Uint8Array|integer} What to search for.
2031* `byteOffset` {integer} Where to begin searching in `buf`. If negative, then
2032  offset is calculated from the end of `buf`. **Default:** `0`.
2033* `encoding` {string} If `value` is a string, this is its encoding.
2034  **Default:** `'utf8'`.
2035* Returns: {boolean} `true` if `value` was found in `buf`, `false` otherwise.
2036
2037Equivalent to [`buf.indexOf() !== -1`][`buf.indexOf()`].
2038
2039```mjs
2040import { Buffer } from 'node:buffer';
2041
2042const buf = Buffer.from('this is a buffer');
2043
2044console.log(buf.includes('this'));
2045// Prints: true
2046console.log(buf.includes('is'));
2047// Prints: true
2048console.log(buf.includes(Buffer.from('a buffer')));
2049// Prints: true
2050console.log(buf.includes(97));
2051// Prints: true (97 is the decimal ASCII value for 'a')
2052console.log(buf.includes(Buffer.from('a buffer example')));
2053// Prints: false
2054console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
2055// Prints: true
2056console.log(buf.includes('this', 4));
2057// Prints: false
2058```
2059
2060```cjs
2061const { Buffer } = require('node:buffer');
2062
2063const buf = Buffer.from('this is a buffer');
2064
2065console.log(buf.includes('this'));
2066// Prints: true
2067console.log(buf.includes('is'));
2068// Prints: true
2069console.log(buf.includes(Buffer.from('a buffer')));
2070// Prints: true
2071console.log(buf.includes(97));
2072// Prints: true (97 is the decimal ASCII value for 'a')
2073console.log(buf.includes(Buffer.from('a buffer example')));
2074// Prints: false
2075console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
2076// Prints: true
2077console.log(buf.includes('this', 4));
2078// Prints: false
2079```
2080
2081### `buf.indexOf(value[, byteOffset][, encoding])`
2082
2083<!-- YAML
2084added: v1.5.0
2085changes:
2086  - version: v8.0.0
2087    pr-url: https://github.com/nodejs/node/pull/10236
2088    description: The `value` can now be a `Uint8Array`.
2089  - version:
2090    - v5.7.0
2091    - v4.4.0
2092    pr-url: https://github.com/nodejs/node/pull/4803
2093    description: When `encoding` is being passed, the `byteOffset` parameter
2094                 is no longer required.
2095-->
2096
2097* `value` {string|Buffer|Uint8Array|integer} What to search for.
2098* `byteOffset` {integer} Where to begin searching in `buf`. If negative, then
2099  offset is calculated from the end of `buf`. **Default:** `0`.
2100* `encoding` {string} If `value` is a string, this is the encoding used to
2101  determine the binary representation of the string that will be searched for in
2102  `buf`. **Default:** `'utf8'`.
2103* Returns: {integer} The index of the first occurrence of `value` in `buf`, or
2104  `-1` if `buf` does not contain `value`.
2105
2106If `value` is:
2107
2108* a string, `value` is interpreted according to the character encoding in
2109  `encoding`.
2110* a `Buffer` or [`Uint8Array`][], `value` will be used in its entirety.
2111  To compare a partial `Buffer`, use [`buf.subarray`][].
2112* a number, `value` will be interpreted as an unsigned 8-bit integer
2113  value between `0` and `255`.
2114
2115```mjs
2116import { Buffer } from 'node:buffer';
2117
2118const buf = Buffer.from('this is a buffer');
2119
2120console.log(buf.indexOf('this'));
2121// Prints: 0
2122console.log(buf.indexOf('is'));
2123// Prints: 2
2124console.log(buf.indexOf(Buffer.from('a buffer')));
2125// Prints: 8
2126console.log(buf.indexOf(97));
2127// Prints: 8 (97 is the decimal ASCII value for 'a')
2128console.log(buf.indexOf(Buffer.from('a buffer example')));
2129// Prints: -1
2130console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
2131// Prints: 8
2132
2133const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
2134
2135console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
2136// Prints: 4
2137console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
2138// Prints: 6
2139```
2140
2141```cjs
2142const { Buffer } = require('node:buffer');
2143
2144const buf = Buffer.from('this is a buffer');
2145
2146console.log(buf.indexOf('this'));
2147// Prints: 0
2148console.log(buf.indexOf('is'));
2149// Prints: 2
2150console.log(buf.indexOf(Buffer.from('a buffer')));
2151// Prints: 8
2152console.log(buf.indexOf(97));
2153// Prints: 8 (97 is the decimal ASCII value for 'a')
2154console.log(buf.indexOf(Buffer.from('a buffer example')));
2155// Prints: -1
2156console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
2157// Prints: 8
2158
2159const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
2160
2161console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
2162// Prints: 4
2163console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
2164// Prints: 6
2165```
2166
2167If `value` is not a string, number, or `Buffer`, this method will throw a
2168`TypeError`. If `value` is a number, it will be coerced to a valid byte value,
2169an integer between 0 and 255.
2170
2171If `byteOffset` is not a number, it will be coerced to a number. If the result
2172of coercion is `NaN` or `0`, then the entire buffer will be searched. This
2173behavior matches [`String.prototype.indexOf()`][].
2174
2175```mjs
2176import { Buffer } from 'node:buffer';
2177
2178const b = Buffer.from('abcdef');
2179
2180// Passing a value that's a number, but not a valid byte.
2181// Prints: 2, equivalent to searching for 99 or 'c'.
2182console.log(b.indexOf(99.9));
2183console.log(b.indexOf(256 + 99));
2184
2185// Passing a byteOffset that coerces to NaN or 0.
2186// Prints: 1, searching the whole buffer.
2187console.log(b.indexOf('b', undefined));
2188console.log(b.indexOf('b', {}));
2189console.log(b.indexOf('b', null));
2190console.log(b.indexOf('b', []));
2191```
2192
2193```cjs
2194const { Buffer } = require('node:buffer');
2195
2196const b = Buffer.from('abcdef');
2197
2198// Passing a value that's a number, but not a valid byte.
2199// Prints: 2, equivalent to searching for 99 or 'c'.
2200console.log(b.indexOf(99.9));
2201console.log(b.indexOf(256 + 99));
2202
2203// Passing a byteOffset that coerces to NaN or 0.
2204// Prints: 1, searching the whole buffer.
2205console.log(b.indexOf('b', undefined));
2206console.log(b.indexOf('b', {}));
2207console.log(b.indexOf('b', null));
2208console.log(b.indexOf('b', []));
2209```
2210
2211If `value` is an empty string or empty `Buffer` and `byteOffset` is less
2212than `buf.length`, `byteOffset` will be returned. If `value` is empty and
2213`byteOffset` is at least `buf.length`, `buf.length` will be returned.
2214
2215### `buf.keys()`
2216
2217<!-- YAML
2218added: v1.1.0
2219-->
2220
2221* Returns: {Iterator}
2222
2223Creates and returns an [iterator][] of `buf` keys (indices).
2224
2225```mjs
2226import { Buffer } from 'node:buffer';
2227
2228const buf = Buffer.from('buffer');
2229
2230for (const key of buf.keys()) {
2231  console.log(key);
2232}
2233// Prints:
2234//   0
2235//   1
2236//   2
2237//   3
2238//   4
2239//   5
2240```
2241
2242```cjs
2243const { Buffer } = require('node:buffer');
2244
2245const buf = Buffer.from('buffer');
2246
2247for (const key of buf.keys()) {
2248  console.log(key);
2249}
2250// Prints:
2251//   0
2252//   1
2253//   2
2254//   3
2255//   4
2256//   5
2257```
2258
2259### `buf.lastIndexOf(value[, byteOffset][, encoding])`
2260
2261<!-- YAML
2262added: v6.0.0
2263changes:
2264  - version: v8.0.0
2265    pr-url: https://github.com/nodejs/node/pull/10236
2266    description: The `value` can now be a `Uint8Array`.
2267-->
2268
2269* `value` {string|Buffer|Uint8Array|integer} What to search for.
2270* `byteOffset` {integer} Where to begin searching in `buf`. If negative, then
2271  offset is calculated from the end of `buf`. **Default:**
2272  `buf.length - 1`.
2273* `encoding` {string} If `value` is a string, this is the encoding used to
2274  determine the binary representation of the string that will be searched for in
2275  `buf`. **Default:** `'utf8'`.
2276* Returns: {integer} The index of the last occurrence of `value` in `buf`, or
2277  `-1` if `buf` does not contain `value`.
2278
2279Identical to [`buf.indexOf()`][], except the last occurrence of `value` is found
2280rather than the first occurrence.
2281
2282```mjs
2283import { Buffer } from 'node:buffer';
2284
2285const buf = Buffer.from('this buffer is a buffer');
2286
2287console.log(buf.lastIndexOf('this'));
2288// Prints: 0
2289console.log(buf.lastIndexOf('buffer'));
2290// Prints: 17
2291console.log(buf.lastIndexOf(Buffer.from('buffer')));
2292// Prints: 17
2293console.log(buf.lastIndexOf(97));
2294// Prints: 15 (97 is the decimal ASCII value for 'a')
2295console.log(buf.lastIndexOf(Buffer.from('yolo')));
2296// Prints: -1
2297console.log(buf.lastIndexOf('buffer', 5));
2298// Prints: 5
2299console.log(buf.lastIndexOf('buffer', 4));
2300// Prints: -1
2301
2302const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
2303
2304console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
2305// Prints: 6
2306console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
2307// Prints: 4
2308```
2309
2310```cjs
2311const { Buffer } = require('node:buffer');
2312
2313const buf = Buffer.from('this buffer is a buffer');
2314
2315console.log(buf.lastIndexOf('this'));
2316// Prints: 0
2317console.log(buf.lastIndexOf('buffer'));
2318// Prints: 17
2319console.log(buf.lastIndexOf(Buffer.from('buffer')));
2320// Prints: 17
2321console.log(buf.lastIndexOf(97));
2322// Prints: 15 (97 is the decimal ASCII value for 'a')
2323console.log(buf.lastIndexOf(Buffer.from('yolo')));
2324// Prints: -1
2325console.log(buf.lastIndexOf('buffer', 5));
2326// Prints: 5
2327console.log(buf.lastIndexOf('buffer', 4));
2328// Prints: -1
2329
2330const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
2331
2332console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
2333// Prints: 6
2334console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
2335// Prints: 4
2336```
2337
2338If `value` is not a string, number, or `Buffer`, this method will throw a
2339`TypeError`. If `value` is a number, it will be coerced to a valid byte value,
2340an integer between 0 and 255.
2341
2342If `byteOffset` is not a number, it will be coerced to a number. Any arguments
2343that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer.
2344This behavior matches [`String.prototype.lastIndexOf()`][].
2345
2346```mjs
2347import { Buffer } from 'node:buffer';
2348
2349const b = Buffer.from('abcdef');
2350
2351// Passing a value that's a number, but not a valid byte.
2352// Prints: 2, equivalent to searching for 99 or 'c'.
2353console.log(b.lastIndexOf(99.9));
2354console.log(b.lastIndexOf(256 + 99));
2355
2356// Passing a byteOffset that coerces to NaN.
2357// Prints: 1, searching the whole buffer.
2358console.log(b.lastIndexOf('b', undefined));
2359console.log(b.lastIndexOf('b', {}));
2360
2361// Passing a byteOffset that coerces to 0.
2362// Prints: -1, equivalent to passing 0.
2363console.log(b.lastIndexOf('b', null));
2364console.log(b.lastIndexOf('b', []));
2365```
2366
2367```cjs
2368const { Buffer } = require('node:buffer');
2369
2370const b = Buffer.from('abcdef');
2371
2372// Passing a value that's a number, but not a valid byte.
2373// Prints: 2, equivalent to searching for 99 or 'c'.
2374console.log(b.lastIndexOf(99.9));
2375console.log(b.lastIndexOf(256 + 99));
2376
2377// Passing a byteOffset that coerces to NaN.
2378// Prints: 1, searching the whole buffer.
2379console.log(b.lastIndexOf('b', undefined));
2380console.log(b.lastIndexOf('b', {}));
2381
2382// Passing a byteOffset that coerces to 0.
2383// Prints: -1, equivalent to passing 0.
2384console.log(b.lastIndexOf('b', null));
2385console.log(b.lastIndexOf('b', []));
2386```
2387
2388If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned.
2389
2390### `buf.length`
2391
2392<!-- YAML
2393added: v0.1.90
2394-->
2395
2396* {integer}
2397
2398Returns the number of bytes in `buf`.
2399
2400```mjs
2401import { Buffer } from 'node:buffer';
2402
2403// Create a `Buffer` and write a shorter string to it using UTF-8.
2404
2405const buf = Buffer.alloc(1234);
2406
2407console.log(buf.length);
2408// Prints: 1234
2409
2410buf.write('some string', 0, 'utf8');
2411
2412console.log(buf.length);
2413// Prints: 1234
2414```
2415
2416```cjs
2417const { Buffer } = require('node:buffer');
2418
2419// Create a `Buffer` and write a shorter string to it using UTF-8.
2420
2421const buf = Buffer.alloc(1234);
2422
2423console.log(buf.length);
2424// Prints: 1234
2425
2426buf.write('some string', 0, 'utf8');
2427
2428console.log(buf.length);
2429// Prints: 1234
2430```
2431
2432### `buf.parent`
2433
2434<!-- YAML
2435deprecated: v8.0.0
2436-->
2437
2438> Stability: 0 - Deprecated: Use [`buf.buffer`][] instead.
2439
2440The `buf.parent` property is a deprecated alias for `buf.buffer`.
2441
2442### `buf.readBigInt64BE([offset])`
2443
2444<!-- YAML
2445added:
2446 - v12.0.0
2447 - v10.20.0
2448-->
2449
2450* `offset` {integer} Number of bytes to skip before starting to read. Must
2451  satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
2452* Returns: {bigint}
2453
2454Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`.
2455
2456Integers read from a `Buffer` are interpreted as two's complement signed
2457values.
2458
2459### `buf.readBigInt64LE([offset])`
2460
2461<!-- YAML
2462added:
2463 - v12.0.0
2464 - v10.20.0
2465-->
2466
2467* `offset` {integer} Number of bytes to skip before starting to read. Must
2468  satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
2469* Returns: {bigint}
2470
2471Reads a signed, little-endian 64-bit integer from `buf` at the specified
2472`offset`.
2473
2474Integers read from a `Buffer` are interpreted as two's complement signed
2475values.
2476
2477### `buf.readBigUInt64BE([offset])`
2478
2479<!-- YAML
2480added:
2481 - v12.0.0
2482 - v10.20.0
2483changes:
2484  - version:
2485    - v14.10.0
2486    - v12.19.0
2487    pr-url: https://github.com/nodejs/node/pull/34960
2488    description: This function is also available as `buf.readBigUint64BE()`.
2489-->
2490
2491* `offset` {integer} Number of bytes to skip before starting to read. Must
2492  satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
2493* Returns: {bigint}
2494
2495Reads an unsigned, big-endian 64-bit integer from `buf` at the specified
2496`offset`.
2497
2498This function is also available under the `readBigUint64BE` alias.
2499
2500```mjs
2501import { Buffer } from 'node:buffer';
2502
2503const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
2504
2505console.log(buf.readBigUInt64BE(0));
2506// Prints: 4294967295n
2507```
2508
2509```cjs
2510const { Buffer } = require('node:buffer');
2511
2512const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
2513
2514console.log(buf.readBigUInt64BE(0));
2515// Prints: 4294967295n
2516```
2517
2518### `buf.readBigUInt64LE([offset])`
2519
2520<!-- YAML
2521added:
2522 - v12.0.0
2523 - v10.20.0
2524changes:
2525  - version:
2526    - v14.10.0
2527    - v12.19.0
2528    pr-url: https://github.com/nodejs/node/pull/34960
2529    description: This function is also available as `buf.readBigUint64LE()`.
2530-->
2531
2532* `offset` {integer} Number of bytes to skip before starting to read. Must
2533  satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
2534* Returns: {bigint}
2535
2536Reads an unsigned, little-endian 64-bit integer from `buf` at the specified
2537`offset`.
2538
2539This function is also available under the `readBigUint64LE` alias.
2540
2541```mjs
2542import { Buffer } from 'node:buffer';
2543
2544const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
2545
2546console.log(buf.readBigUInt64LE(0));
2547// Prints: 18446744069414584320n
2548```
2549
2550```cjs
2551const { Buffer } = require('node:buffer');
2552
2553const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
2554
2555console.log(buf.readBigUInt64LE(0));
2556// Prints: 18446744069414584320n
2557```
2558
2559### `buf.readDoubleBE([offset])`
2560
2561<!-- YAML
2562added: v0.11.15
2563changes:
2564  - version: v10.0.0
2565    pr-url: https://github.com/nodejs/node/pull/18395
2566    description: Removed `noAssert` and no implicit coercion of the offset
2567                 to `uint32` anymore.
2568-->
2569
2570* `offset` {integer} Number of bytes to skip before starting to read. Must
2571  satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
2572* Returns: {number}
2573
2574Reads a 64-bit, big-endian double from `buf` at the specified `offset`.
2575
2576```mjs
2577import { Buffer } from 'node:buffer';
2578
2579const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
2580
2581console.log(buf.readDoubleBE(0));
2582// Prints: 8.20788039913184e-304
2583```
2584
2585```cjs
2586const { Buffer } = require('node:buffer');
2587
2588const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
2589
2590console.log(buf.readDoubleBE(0));
2591// Prints: 8.20788039913184e-304
2592```
2593
2594### `buf.readDoubleLE([offset])`
2595
2596<!-- YAML
2597added: v0.11.15
2598changes:
2599  - version: v10.0.0
2600    pr-url: https://github.com/nodejs/node/pull/18395
2601    description: Removed `noAssert` and no implicit coercion of the offset
2602                 to `uint32` anymore.
2603-->
2604
2605* `offset` {integer} Number of bytes to skip before starting to read. Must
2606  satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
2607* Returns: {number}
2608
2609Reads a 64-bit, little-endian double from `buf` at the specified `offset`.
2610
2611```mjs
2612import { Buffer } from 'node:buffer';
2613
2614const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
2615
2616console.log(buf.readDoubleLE(0));
2617// Prints: 5.447603722011605e-270
2618console.log(buf.readDoubleLE(1));
2619// Throws ERR_OUT_OF_RANGE.
2620```
2621
2622```cjs
2623const { Buffer } = require('node:buffer');
2624
2625const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
2626
2627console.log(buf.readDoubleLE(0));
2628// Prints: 5.447603722011605e-270
2629console.log(buf.readDoubleLE(1));
2630// Throws ERR_OUT_OF_RANGE.
2631```
2632
2633### `buf.readFloatBE([offset])`
2634
2635<!-- YAML
2636added: v0.11.15
2637changes:
2638  - version: v10.0.0
2639    pr-url: https://github.com/nodejs/node/pull/18395
2640    description: Removed `noAssert` and no implicit coercion of the offset
2641                 to `uint32` anymore.
2642-->
2643
2644* `offset` {integer} Number of bytes to skip before starting to read. Must
2645  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
2646* Returns: {number}
2647
2648Reads a 32-bit, big-endian float from `buf` at the specified `offset`.
2649
2650```mjs
2651import { Buffer } from 'node:buffer';
2652
2653const buf = Buffer.from([1, 2, 3, 4]);
2654
2655console.log(buf.readFloatBE(0));
2656// Prints: 2.387939260590663e-38
2657```
2658
2659```cjs
2660const { Buffer } = require('node:buffer');
2661
2662const buf = Buffer.from([1, 2, 3, 4]);
2663
2664console.log(buf.readFloatBE(0));
2665// Prints: 2.387939260590663e-38
2666```
2667
2668### `buf.readFloatLE([offset])`
2669
2670<!-- YAML
2671added: v0.11.15
2672changes:
2673  - version: v10.0.0
2674    pr-url: https://github.com/nodejs/node/pull/18395
2675    description: Removed `noAssert` and no implicit coercion of the offset
2676                 to `uint32` anymore.
2677-->
2678
2679* `offset` {integer} Number of bytes to skip before starting to read. Must
2680  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
2681* Returns: {number}
2682
2683Reads a 32-bit, little-endian float from `buf` at the specified `offset`.
2684
2685```mjs
2686import { Buffer } from 'node:buffer';
2687
2688const buf = Buffer.from([1, 2, 3, 4]);
2689
2690console.log(buf.readFloatLE(0));
2691// Prints: 1.539989614439558e-36
2692console.log(buf.readFloatLE(1));
2693// Throws ERR_OUT_OF_RANGE.
2694```
2695
2696```cjs
2697const { Buffer } = require('node:buffer');
2698
2699const buf = Buffer.from([1, 2, 3, 4]);
2700
2701console.log(buf.readFloatLE(0));
2702// Prints: 1.539989614439558e-36
2703console.log(buf.readFloatLE(1));
2704// Throws ERR_OUT_OF_RANGE.
2705```
2706
2707### `buf.readInt8([offset])`
2708
2709<!-- YAML
2710added: v0.5.0
2711changes:
2712  - version: v10.0.0
2713    pr-url: https://github.com/nodejs/node/pull/18395
2714    description: Removed `noAssert` and no implicit coercion of the offset
2715                 to `uint32` anymore.
2716-->
2717
2718* `offset` {integer} Number of bytes to skip before starting to read. Must
2719  satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
2720* Returns: {integer}
2721
2722Reads a signed 8-bit integer from `buf` at the specified `offset`.
2723
2724Integers read from a `Buffer` are interpreted as two's complement signed values.
2725
2726```mjs
2727import { Buffer } from 'node:buffer';
2728
2729const buf = Buffer.from([-1, 5]);
2730
2731console.log(buf.readInt8(0));
2732// Prints: -1
2733console.log(buf.readInt8(1));
2734// Prints: 5
2735console.log(buf.readInt8(2));
2736// Throws ERR_OUT_OF_RANGE.
2737```
2738
2739```cjs
2740const { Buffer } = require('node:buffer');
2741
2742const buf = Buffer.from([-1, 5]);
2743
2744console.log(buf.readInt8(0));
2745// Prints: -1
2746console.log(buf.readInt8(1));
2747// Prints: 5
2748console.log(buf.readInt8(2));
2749// Throws ERR_OUT_OF_RANGE.
2750```
2751
2752### `buf.readInt16BE([offset])`
2753
2754<!-- YAML
2755added: v0.5.5
2756changes:
2757  - version: v10.0.0
2758    pr-url: https://github.com/nodejs/node/pull/18395
2759    description: Removed `noAssert` and no implicit coercion of the offset
2760                 to `uint32` anymore.
2761-->
2762
2763* `offset` {integer} Number of bytes to skip before starting to read. Must
2764  satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
2765* Returns: {integer}
2766
2767Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`.
2768
2769Integers read from a `Buffer` are interpreted as two's complement signed values.
2770
2771```mjs
2772import { Buffer } from 'node:buffer';
2773
2774const buf = Buffer.from([0, 5]);
2775
2776console.log(buf.readInt16BE(0));
2777// Prints: 5
2778```
2779
2780```cjs
2781const { Buffer } = require('node:buffer');
2782
2783const buf = Buffer.from([0, 5]);
2784
2785console.log(buf.readInt16BE(0));
2786// Prints: 5
2787```
2788
2789### `buf.readInt16LE([offset])`
2790
2791<!-- YAML
2792added: v0.5.5
2793changes:
2794  - version: v10.0.0
2795    pr-url: https://github.com/nodejs/node/pull/18395
2796    description: Removed `noAssert` and no implicit coercion of the offset
2797                 to `uint32` anymore.
2798-->
2799
2800* `offset` {integer} Number of bytes to skip before starting to read. Must
2801  satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
2802* Returns: {integer}
2803
2804Reads a signed, little-endian 16-bit integer from `buf` at the specified
2805`offset`.
2806
2807Integers read from a `Buffer` are interpreted as two's complement signed values.
2808
2809```mjs
2810import { Buffer } from 'node:buffer';
2811
2812const buf = Buffer.from([0, 5]);
2813
2814console.log(buf.readInt16LE(0));
2815// Prints: 1280
2816console.log(buf.readInt16LE(1));
2817// Throws ERR_OUT_OF_RANGE.
2818```
2819
2820```cjs
2821const { Buffer } = require('node:buffer');
2822
2823const buf = Buffer.from([0, 5]);
2824
2825console.log(buf.readInt16LE(0));
2826// Prints: 1280
2827console.log(buf.readInt16LE(1));
2828// Throws ERR_OUT_OF_RANGE.
2829```
2830
2831### `buf.readInt32BE([offset])`
2832
2833<!-- YAML
2834added: v0.5.5
2835changes:
2836  - version: v10.0.0
2837    pr-url: https://github.com/nodejs/node/pull/18395
2838    description: Removed `noAssert` and no implicit coercion of the offset
2839                 to `uint32` anymore.
2840-->
2841
2842* `offset` {integer} Number of bytes to skip before starting to read. Must
2843  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
2844* Returns: {integer}
2845
2846Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`.
2847
2848Integers read from a `Buffer` are interpreted as two's complement signed values.
2849
2850```mjs
2851import { Buffer } from 'node:buffer';
2852
2853const buf = Buffer.from([0, 0, 0, 5]);
2854
2855console.log(buf.readInt32BE(0));
2856// Prints: 5
2857```
2858
2859```cjs
2860const { Buffer } = require('node:buffer');
2861
2862const buf = Buffer.from([0, 0, 0, 5]);
2863
2864console.log(buf.readInt32BE(0));
2865// Prints: 5
2866```
2867
2868### `buf.readInt32LE([offset])`
2869
2870<!-- YAML
2871added: v0.5.5
2872changes:
2873  - version: v10.0.0
2874    pr-url: https://github.com/nodejs/node/pull/18395
2875    description: Removed `noAssert` and no implicit coercion of the offset
2876                 to `uint32` anymore.
2877-->
2878
2879* `offset` {integer} Number of bytes to skip before starting to read. Must
2880  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
2881* Returns: {integer}
2882
2883Reads a signed, little-endian 32-bit integer from `buf` at the specified
2884`offset`.
2885
2886Integers read from a `Buffer` are interpreted as two's complement signed values.
2887
2888```mjs
2889import { Buffer } from 'node:buffer';
2890
2891const buf = Buffer.from([0, 0, 0, 5]);
2892
2893console.log(buf.readInt32LE(0));
2894// Prints: 83886080
2895console.log(buf.readInt32LE(1));
2896// Throws ERR_OUT_OF_RANGE.
2897```
2898
2899```cjs
2900const { Buffer } = require('node:buffer');
2901
2902const buf = Buffer.from([0, 0, 0, 5]);
2903
2904console.log(buf.readInt32LE(0));
2905// Prints: 83886080
2906console.log(buf.readInt32LE(1));
2907// Throws ERR_OUT_OF_RANGE.
2908```
2909
2910### `buf.readIntBE(offset, byteLength)`
2911
2912<!-- YAML
2913added: v0.11.15
2914changes:
2915  - version: v10.0.0
2916    pr-url: https://github.com/nodejs/node/pull/18395
2917    description: Removed `noAssert` and no implicit coercion of the offset
2918                 and `byteLength` to `uint32` anymore.
2919-->
2920
2921* `offset` {integer} Number of bytes to skip before starting to read. Must
2922  satisfy `0 <= offset <= buf.length - byteLength`.
2923* `byteLength` {integer} Number of bytes to read. Must satisfy
2924  `0 < byteLength <= 6`.
2925* Returns: {integer}
2926
2927Reads `byteLength` number of bytes from `buf` at the specified `offset`
2928and interprets the result as a big-endian, two's complement signed value
2929supporting up to 48 bits of accuracy.
2930
2931```mjs
2932import { Buffer } from 'node:buffer';
2933
2934const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
2935
2936console.log(buf.readIntBE(0, 6).toString(16));
2937// Prints: 1234567890ab
2938console.log(buf.readIntBE(1, 6).toString(16));
2939// Throws ERR_OUT_OF_RANGE.
2940console.log(buf.readIntBE(1, 0).toString(16));
2941// Throws ERR_OUT_OF_RANGE.
2942```
2943
2944```cjs
2945const { Buffer } = require('node:buffer');
2946
2947const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
2948
2949console.log(buf.readIntBE(0, 6).toString(16));
2950// Prints: 1234567890ab
2951console.log(buf.readIntBE(1, 6).toString(16));
2952// Throws ERR_OUT_OF_RANGE.
2953console.log(buf.readIntBE(1, 0).toString(16));
2954// Throws ERR_OUT_OF_RANGE.
2955```
2956
2957### `buf.readIntLE(offset, byteLength)`
2958
2959<!-- YAML
2960added: v0.11.15
2961changes:
2962  - version: v10.0.0
2963    pr-url: https://github.com/nodejs/node/pull/18395
2964    description: Removed `noAssert` and no implicit coercion of the offset
2965                 and `byteLength` to `uint32` anymore.
2966-->
2967
2968* `offset` {integer} Number of bytes to skip before starting to read. Must
2969  satisfy `0 <= offset <= buf.length - byteLength`.
2970* `byteLength` {integer} Number of bytes to read. Must satisfy
2971  `0 < byteLength <= 6`.
2972* Returns: {integer}
2973
2974Reads `byteLength` number of bytes from `buf` at the specified `offset`
2975and interprets the result as a little-endian, two's complement signed value
2976supporting up to 48 bits of accuracy.
2977
2978```mjs
2979import { Buffer } from 'node:buffer';
2980
2981const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
2982
2983console.log(buf.readIntLE(0, 6).toString(16));
2984// Prints: -546f87a9cbee
2985```
2986
2987```cjs
2988const { Buffer } = require('node:buffer');
2989
2990const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
2991
2992console.log(buf.readIntLE(0, 6).toString(16));
2993// Prints: -546f87a9cbee
2994```
2995
2996### `buf.readUInt8([offset])`
2997
2998<!-- YAML
2999added: v0.5.0
3000changes:
3001  - version:
3002    - v14.9.0
3003    - v12.19.0
3004    pr-url: https://github.com/nodejs/node/pull/34729
3005    description: This function is also available as `buf.readUint8()`.
3006  - version: v10.0.0
3007    pr-url: https://github.com/nodejs/node/pull/18395
3008    description: Removed `noAssert` and no implicit coercion of the offset
3009                 to `uint32` anymore.
3010-->
3011
3012* `offset` {integer} Number of bytes to skip before starting to read. Must
3013  satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
3014* Returns: {integer}
3015
3016Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
3017
3018This function is also available under the `readUint8` alias.
3019
3020```mjs
3021import { Buffer } from 'node:buffer';
3022
3023const buf = Buffer.from([1, -2]);
3024
3025console.log(buf.readUInt8(0));
3026// Prints: 1
3027console.log(buf.readUInt8(1));
3028// Prints: 254
3029console.log(buf.readUInt8(2));
3030// Throws ERR_OUT_OF_RANGE.
3031```
3032
3033```cjs
3034const { Buffer } = require('node:buffer');
3035
3036const buf = Buffer.from([1, -2]);
3037
3038console.log(buf.readUInt8(0));
3039// Prints: 1
3040console.log(buf.readUInt8(1));
3041// Prints: 254
3042console.log(buf.readUInt8(2));
3043// Throws ERR_OUT_OF_RANGE.
3044```
3045
3046### `buf.readUInt16BE([offset])`
3047
3048<!-- YAML
3049added: v0.5.5
3050changes:
3051  - version:
3052    - v14.9.0
3053    - v12.19.0
3054    pr-url: https://github.com/nodejs/node/pull/34729
3055    description: This function is also available as `buf.readUint16BE()`.
3056  - version: v10.0.0
3057    pr-url: https://github.com/nodejs/node/pull/18395
3058    description: Removed `noAssert` and no implicit coercion of the offset
3059                 to `uint32` anymore.
3060-->
3061
3062* `offset` {integer} Number of bytes to skip before starting to read. Must
3063  satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
3064* Returns: {integer}
3065
3066Reads an unsigned, big-endian 16-bit integer from `buf` at the specified
3067`offset`.
3068
3069This function is also available under the `readUint16BE` alias.
3070
3071```mjs
3072import { Buffer } from 'node:buffer';
3073
3074const buf = Buffer.from([0x12, 0x34, 0x56]);
3075
3076console.log(buf.readUInt16BE(0).toString(16));
3077// Prints: 1234
3078console.log(buf.readUInt16BE(1).toString(16));
3079// Prints: 3456
3080```
3081
3082```cjs
3083const { Buffer } = require('node:buffer');
3084
3085const buf = Buffer.from([0x12, 0x34, 0x56]);
3086
3087console.log(buf.readUInt16BE(0).toString(16));
3088// Prints: 1234
3089console.log(buf.readUInt16BE(1).toString(16));
3090// Prints: 3456
3091```
3092
3093### `buf.readUInt16LE([offset])`
3094
3095<!-- YAML
3096added: v0.5.5
3097changes:
3098  - version:
3099    - v14.9.0
3100    - v12.19.0
3101    pr-url: https://github.com/nodejs/node/pull/34729
3102    description: This function is also available as `buf.readUint16LE()`.
3103  - version: v10.0.0
3104    pr-url: https://github.com/nodejs/node/pull/18395
3105    description: Removed `noAssert` and no implicit coercion of the offset
3106                 to `uint32` anymore.
3107-->
3108
3109* `offset` {integer} Number of bytes to skip before starting to read. Must
3110  satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
3111* Returns: {integer}
3112
3113Reads an unsigned, little-endian 16-bit integer from `buf` at the specified
3114`offset`.
3115
3116This function is also available under the `readUint16LE` alias.
3117
3118```mjs
3119import { Buffer } from 'node:buffer';
3120
3121const buf = Buffer.from([0x12, 0x34, 0x56]);
3122
3123console.log(buf.readUInt16LE(0).toString(16));
3124// Prints: 3412
3125console.log(buf.readUInt16LE(1).toString(16));
3126// Prints: 5634
3127console.log(buf.readUInt16LE(2).toString(16));
3128// Throws ERR_OUT_OF_RANGE.
3129```
3130
3131```cjs
3132const { Buffer } = require('node:buffer');
3133
3134const buf = Buffer.from([0x12, 0x34, 0x56]);
3135
3136console.log(buf.readUInt16LE(0).toString(16));
3137// Prints: 3412
3138console.log(buf.readUInt16LE(1).toString(16));
3139// Prints: 5634
3140console.log(buf.readUInt16LE(2).toString(16));
3141// Throws ERR_OUT_OF_RANGE.
3142```
3143
3144### `buf.readUInt32BE([offset])`
3145
3146<!-- YAML
3147added: v0.5.5
3148changes:
3149  - version:
3150    - v14.9.0
3151    - v12.19.0
3152    pr-url: https://github.com/nodejs/node/pull/34729
3153    description: This function is also available as `buf.readUint32BE()`.
3154  - version: v10.0.0
3155    pr-url: https://github.com/nodejs/node/pull/18395
3156    description: Removed `noAssert` and no implicit coercion of the offset
3157                 to `uint32` anymore.
3158-->
3159
3160* `offset` {integer} Number of bytes to skip before starting to read. Must
3161  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
3162* Returns: {integer}
3163
3164Reads an unsigned, big-endian 32-bit integer from `buf` at the specified
3165`offset`.
3166
3167This function is also available under the `readUint32BE` alias.
3168
3169```mjs
3170import { Buffer } from 'node:buffer';
3171
3172const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
3173
3174console.log(buf.readUInt32BE(0).toString(16));
3175// Prints: 12345678
3176```
3177
3178```cjs
3179const { Buffer } = require('node:buffer');
3180
3181const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
3182
3183console.log(buf.readUInt32BE(0).toString(16));
3184// Prints: 12345678
3185```
3186
3187### `buf.readUInt32LE([offset])`
3188
3189<!-- YAML
3190added: v0.5.5
3191changes:
3192  - version:
3193    - v14.9.0
3194    - v12.19.0
3195    pr-url: https://github.com/nodejs/node/pull/34729
3196    description: This function is also available as `buf.readUint32LE()`.
3197  - version: v10.0.0
3198    pr-url: https://github.com/nodejs/node/pull/18395
3199    description: Removed `noAssert` and no implicit coercion of the offset
3200                 to `uint32` anymore.
3201-->
3202
3203* `offset` {integer} Number of bytes to skip before starting to read. Must
3204  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
3205* Returns: {integer}
3206
3207Reads an unsigned, little-endian 32-bit integer from `buf` at the specified
3208`offset`.
3209
3210This function is also available under the `readUint32LE` alias.
3211
3212```mjs
3213import { Buffer } from 'node:buffer';
3214
3215const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
3216
3217console.log(buf.readUInt32LE(0).toString(16));
3218// Prints: 78563412
3219console.log(buf.readUInt32LE(1).toString(16));
3220// Throws ERR_OUT_OF_RANGE.
3221```
3222
3223```cjs
3224const { Buffer } = require('node:buffer');
3225
3226const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
3227
3228console.log(buf.readUInt32LE(0).toString(16));
3229// Prints: 78563412
3230console.log(buf.readUInt32LE(1).toString(16));
3231// Throws ERR_OUT_OF_RANGE.
3232```
3233
3234### `buf.readUIntBE(offset, byteLength)`
3235
3236<!-- YAML
3237added: v0.11.15
3238changes:
3239  - version:
3240    - v14.9.0
3241    - v12.19.0
3242    pr-url: https://github.com/nodejs/node/pull/34729
3243    description: This function is also available as `buf.readUintBE()`.
3244  - version: v10.0.0
3245    pr-url: https://github.com/nodejs/node/pull/18395
3246    description: Removed `noAssert` and no implicit coercion of the offset
3247                 and `byteLength` to `uint32` anymore.
3248-->
3249
3250* `offset` {integer} Number of bytes to skip before starting to read. Must
3251  satisfy `0 <= offset <= buf.length - byteLength`.
3252* `byteLength` {integer} Number of bytes to read. Must satisfy
3253  `0 < byteLength <= 6`.
3254* Returns: {integer}
3255
3256Reads `byteLength` number of bytes from `buf` at the specified `offset`
3257and interprets the result as an unsigned big-endian integer supporting
3258up to 48 bits of accuracy.
3259
3260This function is also available under the `readUintBE` alias.
3261
3262```mjs
3263import { Buffer } from 'node:buffer';
3264
3265const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
3266
3267console.log(buf.readUIntBE(0, 6).toString(16));
3268// Prints: 1234567890ab
3269console.log(buf.readUIntBE(1, 6).toString(16));
3270// Throws ERR_OUT_OF_RANGE.
3271```
3272
3273```cjs
3274const { Buffer } = require('node:buffer');
3275
3276const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
3277
3278console.log(buf.readUIntBE(0, 6).toString(16));
3279// Prints: 1234567890ab
3280console.log(buf.readUIntBE(1, 6).toString(16));
3281// Throws ERR_OUT_OF_RANGE.
3282```
3283
3284### `buf.readUIntLE(offset, byteLength)`
3285
3286<!-- YAML
3287added: v0.11.15
3288changes:
3289  - version:
3290    - v14.9.0
3291    - v12.19.0
3292    pr-url: https://github.com/nodejs/node/pull/34729
3293    description: This function is also available as `buf.readUintLE()`.
3294  - version: v10.0.0
3295    pr-url: https://github.com/nodejs/node/pull/18395
3296    description: Removed `noAssert` and no implicit coercion of the offset
3297                 and `byteLength` to `uint32` anymore.
3298-->
3299
3300* `offset` {integer} Number of bytes to skip before starting to read. Must
3301  satisfy `0 <= offset <= buf.length - byteLength`.
3302* `byteLength` {integer} Number of bytes to read. Must satisfy
3303  `0 < byteLength <= 6`.
3304* Returns: {integer}
3305
3306Reads `byteLength` number of bytes from `buf` at the specified `offset`
3307and interprets the result as an unsigned, little-endian integer supporting
3308up to 48 bits of accuracy.
3309
3310This function is also available under the `readUintLE` alias.
3311
3312```mjs
3313import { Buffer } from 'node:buffer';
3314
3315const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
3316
3317console.log(buf.readUIntLE(0, 6).toString(16));
3318// Prints: ab9078563412
3319```
3320
3321```cjs
3322const { Buffer } = require('node:buffer');
3323
3324const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
3325
3326console.log(buf.readUIntLE(0, 6).toString(16));
3327// Prints: ab9078563412
3328```
3329
3330### `buf.subarray([start[, end]])`
3331
3332<!-- YAML
3333added: v3.0.0
3334-->
3335
3336* `start` {integer} Where the new `Buffer` will start. **Default:** `0`.
3337* `end` {integer} Where the new `Buffer` will end (not inclusive).
3338  **Default:** [`buf.length`][].
3339* Returns: {Buffer}
3340
3341Returns a new `Buffer` that references the same memory as the original, but
3342offset and cropped by the `start` and `end` indices.
3343
3344Specifying `end` greater than [`buf.length`][] will return the same result as
3345that of `end` equal to [`buf.length`][].
3346
3347This method is inherited from [`TypedArray.prototype.subarray()`][].
3348
3349Modifying the new `Buffer` slice will modify the memory in the original `Buffer`
3350because the allocated memory of the two objects overlap.
3351
3352```mjs
3353import { Buffer } from 'node:buffer';
3354
3355// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
3356// from the original `Buffer`.
3357
3358const buf1 = Buffer.allocUnsafe(26);
3359
3360for (let i = 0; i < 26; i++) {
3361  // 97 is the decimal ASCII value for 'a'.
3362  buf1[i] = i + 97;
3363}
3364
3365const buf2 = buf1.subarray(0, 3);
3366
3367console.log(buf2.toString('ascii', 0, buf2.length));
3368// Prints: abc
3369
3370buf1[0] = 33;
3371
3372console.log(buf2.toString('ascii', 0, buf2.length));
3373// Prints: !bc
3374```
3375
3376```cjs
3377const { Buffer } = require('node:buffer');
3378
3379// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
3380// from the original `Buffer`.
3381
3382const buf1 = Buffer.allocUnsafe(26);
3383
3384for (let i = 0; i < 26; i++) {
3385  // 97 is the decimal ASCII value for 'a'.
3386  buf1[i] = i + 97;
3387}
3388
3389const buf2 = buf1.subarray(0, 3);
3390
3391console.log(buf2.toString('ascii', 0, buf2.length));
3392// Prints: abc
3393
3394buf1[0] = 33;
3395
3396console.log(buf2.toString('ascii', 0, buf2.length));
3397// Prints: !bc
3398```
3399
3400Specifying negative indexes causes the slice to be generated relative to the
3401end of `buf` rather than the beginning.
3402
3403```mjs
3404import { Buffer } from 'node:buffer';
3405
3406const buf = Buffer.from('buffer');
3407
3408console.log(buf.subarray(-6, -1).toString());
3409// Prints: buffe
3410// (Equivalent to buf.subarray(0, 5).)
3411
3412console.log(buf.subarray(-6, -2).toString());
3413// Prints: buff
3414// (Equivalent to buf.subarray(0, 4).)
3415
3416console.log(buf.subarray(-5, -2).toString());
3417// Prints: uff
3418// (Equivalent to buf.subarray(1, 4).)
3419```
3420
3421```cjs
3422const { Buffer } = require('node:buffer');
3423
3424const buf = Buffer.from('buffer');
3425
3426console.log(buf.subarray(-6, -1).toString());
3427// Prints: buffe
3428// (Equivalent to buf.subarray(0, 5).)
3429
3430console.log(buf.subarray(-6, -2).toString());
3431// Prints: buff
3432// (Equivalent to buf.subarray(0, 4).)
3433
3434console.log(buf.subarray(-5, -2).toString());
3435// Prints: uff
3436// (Equivalent to buf.subarray(1, 4).)
3437```
3438
3439### `buf.slice([start[, end]])`
3440
3441<!-- YAML
3442added: v0.3.0
3443changes:
3444  - version: v17.5.0
3445    pr-url: https://github.com/nodejs/node/pull/41596
3446    description: The buf.slice() method has been deprecated.
3447  - version:
3448    - v7.1.0
3449    - v6.9.2
3450    pr-url: https://github.com/nodejs/node/pull/9341
3451    description: Coercing the offsets to integers now handles values outside
3452                 the 32-bit integer range properly.
3453  - version: v7.0.0
3454    pr-url: https://github.com/nodejs/node/pull/9101
3455    description: All offsets are now coerced to integers before doing any
3456                 calculations with them.
3457-->
3458
3459* `start` {integer} Where the new `Buffer` will start. **Default:** `0`.
3460* `end` {integer} Where the new `Buffer` will end (not inclusive).
3461  **Default:** [`buf.length`][].
3462* Returns: {Buffer}
3463
3464> Stability: 0 - Deprecated: Use [`buf.subarray`][] instead.
3465
3466Returns a new `Buffer` that references the same memory as the original, but
3467offset and cropped by the `start` and `end` indices.
3468
3469This method is not compatible with the `Uint8Array.prototype.slice()`,
3470which is a superclass of `Buffer`. To copy the slice, use
3471`Uint8Array.prototype.slice()`.
3472
3473```mjs
3474import { Buffer } from 'node:buffer';
3475
3476const buf = Buffer.from('buffer');
3477
3478const copiedBuf = Uint8Array.prototype.slice.call(buf);
3479copiedBuf[0]++;
3480console.log(copiedBuf.toString());
3481// Prints: cuffer
3482
3483console.log(buf.toString());
3484// Prints: buffer
3485
3486// With buf.slice(), the original buffer is modified.
3487const notReallyCopiedBuf = buf.slice();
3488notReallyCopiedBuf[0]++;
3489console.log(notReallyCopiedBuf.toString());
3490// Prints: cuffer
3491console.log(buf.toString());
3492// Also prints: cuffer (!)
3493```
3494
3495```cjs
3496const { Buffer } = require('node:buffer');
3497
3498const buf = Buffer.from('buffer');
3499
3500const copiedBuf = Uint8Array.prototype.slice.call(buf);
3501copiedBuf[0]++;
3502console.log(copiedBuf.toString());
3503// Prints: cuffer
3504
3505console.log(buf.toString());
3506// Prints: buffer
3507
3508// With buf.slice(), the original buffer is modified.
3509const notReallyCopiedBuf = buf.slice();
3510notReallyCopiedBuf[0]++;
3511console.log(notReallyCopiedBuf.toString());
3512// Prints: cuffer
3513console.log(buf.toString());
3514// Also prints: cuffer (!)
3515```
3516
3517### `buf.swap16()`
3518
3519<!-- YAML
3520added: v5.10.0
3521-->
3522
3523* Returns: {Buffer} A reference to `buf`.
3524
3525Interprets `buf` as an array of unsigned 16-bit integers and swaps the
3526byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][]
3527is not a multiple of 2.
3528
3529```mjs
3530import { Buffer } from 'node:buffer';
3531
3532const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
3533
3534console.log(buf1);
3535// Prints: <Buffer 01 02 03 04 05 06 07 08>
3536
3537buf1.swap16();
3538
3539console.log(buf1);
3540// Prints: <Buffer 02 01 04 03 06 05 08 07>
3541
3542const buf2 = Buffer.from([0x1, 0x2, 0x3]);
3543
3544buf2.swap16();
3545// Throws ERR_INVALID_BUFFER_SIZE.
3546```
3547
3548```cjs
3549const { Buffer } = require('node:buffer');
3550
3551const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
3552
3553console.log(buf1);
3554// Prints: <Buffer 01 02 03 04 05 06 07 08>
3555
3556buf1.swap16();
3557
3558console.log(buf1);
3559// Prints: <Buffer 02 01 04 03 06 05 08 07>
3560
3561const buf2 = Buffer.from([0x1, 0x2, 0x3]);
3562
3563buf2.swap16();
3564// Throws ERR_INVALID_BUFFER_SIZE.
3565```
3566
3567One convenient use of `buf.swap16()` is to perform a fast in-place conversion
3568between UTF-16 little-endian and UTF-16 big-endian:
3569
3570```mjs
3571import { Buffer } from 'node:buffer';
3572
3573const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
3574buf.swap16(); // Convert to big-endian UTF-16 text.
3575```
3576
3577```cjs
3578const { Buffer } = require('node:buffer');
3579
3580const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
3581buf.swap16(); // Convert to big-endian UTF-16 text.
3582```
3583
3584### `buf.swap32()`
3585
3586<!-- YAML
3587added: v5.10.0
3588-->
3589
3590* Returns: {Buffer} A reference to `buf`.
3591
3592Interprets `buf` as an array of unsigned 32-bit integers and swaps the
3593byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][]
3594is not a multiple of 4.
3595
3596```mjs
3597import { Buffer } from 'node:buffer';
3598
3599const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
3600
3601console.log(buf1);
3602// Prints: <Buffer 01 02 03 04 05 06 07 08>
3603
3604buf1.swap32();
3605
3606console.log(buf1);
3607// Prints: <Buffer 04 03 02 01 08 07 06 05>
3608
3609const buf2 = Buffer.from([0x1, 0x2, 0x3]);
3610
3611buf2.swap32();
3612// Throws ERR_INVALID_BUFFER_SIZE.
3613```
3614
3615```cjs
3616const { Buffer } = require('node:buffer');
3617
3618const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
3619
3620console.log(buf1);
3621// Prints: <Buffer 01 02 03 04 05 06 07 08>
3622
3623buf1.swap32();
3624
3625console.log(buf1);
3626// Prints: <Buffer 04 03 02 01 08 07 06 05>
3627
3628const buf2 = Buffer.from([0x1, 0x2, 0x3]);
3629
3630buf2.swap32();
3631// Throws ERR_INVALID_BUFFER_SIZE.
3632```
3633
3634### `buf.swap64()`
3635
3636<!-- YAML
3637added: v6.3.0
3638-->
3639
3640* Returns: {Buffer} A reference to `buf`.
3641
3642Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_.
3643Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 8.
3644
3645```mjs
3646import { Buffer } from 'node:buffer';
3647
3648const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
3649
3650console.log(buf1);
3651// Prints: <Buffer 01 02 03 04 05 06 07 08>
3652
3653buf1.swap64();
3654
3655console.log(buf1);
3656// Prints: <Buffer 08 07 06 05 04 03 02 01>
3657
3658const buf2 = Buffer.from([0x1, 0x2, 0x3]);
3659
3660buf2.swap64();
3661// Throws ERR_INVALID_BUFFER_SIZE.
3662```
3663
3664```cjs
3665const { Buffer } = require('node:buffer');
3666
3667const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
3668
3669console.log(buf1);
3670// Prints: <Buffer 01 02 03 04 05 06 07 08>
3671
3672buf1.swap64();
3673
3674console.log(buf1);
3675// Prints: <Buffer 08 07 06 05 04 03 02 01>
3676
3677const buf2 = Buffer.from([0x1, 0x2, 0x3]);
3678
3679buf2.swap64();
3680// Throws ERR_INVALID_BUFFER_SIZE.
3681```
3682
3683### `buf.toJSON()`
3684
3685<!-- YAML
3686added: v0.9.2
3687-->
3688
3689* Returns: {Object}
3690
3691Returns a JSON representation of `buf`. [`JSON.stringify()`][] implicitly calls
3692this function when stringifying a `Buffer` instance.
3693
3694`Buffer.from()` accepts objects in the format returned from this method.
3695In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`.
3696
3697```mjs
3698import { Buffer } from 'node:buffer';
3699
3700const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
3701const json = JSON.stringify(buf);
3702
3703console.log(json);
3704// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
3705
3706const copy = JSON.parse(json, (key, value) => {
3707  return value && value.type === 'Buffer' ?
3708    Buffer.from(value) :
3709    value;
3710});
3711
3712console.log(copy);
3713// Prints: <Buffer 01 02 03 04 05>
3714```
3715
3716```cjs
3717const { Buffer } = require('node:buffer');
3718
3719const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
3720const json = JSON.stringify(buf);
3721
3722console.log(json);
3723// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
3724
3725const copy = JSON.parse(json, (key, value) => {
3726  return value && value.type === 'Buffer' ?
3727    Buffer.from(value) :
3728    value;
3729});
3730
3731console.log(copy);
3732// Prints: <Buffer 01 02 03 04 05>
3733```
3734
3735### `buf.toString([encoding[, start[, end]]])`
3736
3737<!-- YAML
3738added: v0.1.90
3739-->
3740
3741* `encoding` {string} The character encoding to use. **Default:** `'utf8'`.
3742* `start` {integer} The byte offset to start decoding at. **Default:** `0`.
3743* `end` {integer} The byte offset to stop decoding at (not inclusive).
3744  **Default:** [`buf.length`][].
3745* Returns: {string}
3746
3747Decodes `buf` to a string according to the specified character encoding in
3748`encoding`. `start` and `end` may be passed to decode only a subset of `buf`.
3749
3750If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8,
3751then each invalid byte is replaced with the replacement character `U+FFFD`.
3752
3753The maximum length of a string instance (in UTF-16 code units) is available
3754as [`buffer.constants.MAX_STRING_LENGTH`][].
3755
3756```mjs
3757import { Buffer } from 'node:buffer';
3758
3759const buf1 = Buffer.allocUnsafe(26);
3760
3761for (let i = 0; i < 26; i++) {
3762  // 97 is the decimal ASCII value for 'a'.
3763  buf1[i] = i + 97;
3764}
3765
3766console.log(buf1.toString('utf8'));
3767// Prints: abcdefghijklmnopqrstuvwxyz
3768console.log(buf1.toString('utf8', 0, 5));
3769// Prints: abcde
3770
3771const buf2 = Buffer.from('tést');
3772
3773console.log(buf2.toString('hex'));
3774// Prints: 74c3a97374
3775console.log(buf2.toString('utf8', 0, 3));
3776// Prints: té
3777console.log(buf2.toString(undefined, 0, 3));
3778// Prints: té
3779```
3780
3781```cjs
3782const { Buffer } = require('node:buffer');
3783
3784const buf1 = Buffer.allocUnsafe(26);
3785
3786for (let i = 0; i < 26; i++) {
3787  // 97 is the decimal ASCII value for 'a'.
3788  buf1[i] = i + 97;
3789}
3790
3791console.log(buf1.toString('utf8'));
3792// Prints: abcdefghijklmnopqrstuvwxyz
3793console.log(buf1.toString('utf8', 0, 5));
3794// Prints: abcde
3795
3796const buf2 = Buffer.from('tést');
3797
3798console.log(buf2.toString('hex'));
3799// Prints: 74c3a97374
3800console.log(buf2.toString('utf8', 0, 3));
3801// Prints: té
3802console.log(buf2.toString(undefined, 0, 3));
3803// Prints: té
3804```
3805
3806### `buf.values()`
3807
3808<!-- YAML
3809added: v1.1.0
3810-->
3811
3812* Returns: {Iterator}
3813
3814Creates and returns an [iterator][] for `buf` values (bytes). This function is
3815called automatically when a `Buffer` is used in a `for..of` statement.
3816
3817```mjs
3818import { Buffer } from 'node:buffer';
3819
3820const buf = Buffer.from('buffer');
3821
3822for (const value of buf.values()) {
3823  console.log(value);
3824}
3825// Prints:
3826//   98
3827//   117
3828//   102
3829//   102
3830//   101
3831//   114
3832
3833for (const value of buf) {
3834  console.log(value);
3835}
3836// Prints:
3837//   98
3838//   117
3839//   102
3840//   102
3841//   101
3842//   114
3843```
3844
3845```cjs
3846const { Buffer } = require('node:buffer');
3847
3848const buf = Buffer.from('buffer');
3849
3850for (const value of buf.values()) {
3851  console.log(value);
3852}
3853// Prints:
3854//   98
3855//   117
3856//   102
3857//   102
3858//   101
3859//   114
3860
3861for (const value of buf) {
3862  console.log(value);
3863}
3864// Prints:
3865//   98
3866//   117
3867//   102
3868//   102
3869//   101
3870//   114
3871```
3872
3873### `buf.write(string[, offset[, length]][, encoding])`
3874
3875<!-- YAML
3876added: v0.1.90
3877-->
3878
3879* `string` {string} String to write to `buf`.
3880* `offset` {integer} Number of bytes to skip before starting to write `string`.
3881  **Default:** `0`.
3882* `length` {integer} Maximum number of bytes to write (written bytes will not
3883  exceed `buf.length - offset`). **Default:** `buf.length - offset`.
3884* `encoding` {string} The character encoding of `string`. **Default:** `'utf8'`.
3885* Returns: {integer} Number of bytes written.
3886
3887Writes `string` to `buf` at `offset` according to the character encoding in
3888`encoding`. The `length` parameter is the number of bytes to write. If `buf` did
3889not contain enough space to fit the entire string, only part of `string` will be
3890written. However, partially encoded characters will not be written.
3891
3892```mjs
3893import { Buffer } from 'node:buffer';
3894
3895const buf = Buffer.alloc(256);
3896
3897const len = buf.write('\u00bd + \u00bc = \u00be', 0);
3898
3899console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
3900// Prints: 12 bytes: ½ + ¼ = ¾
3901
3902const buffer = Buffer.alloc(10);
3903
3904const length = buffer.write('abcd', 8);
3905
3906console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
3907// Prints: 2 bytes : ab
3908```
3909
3910```cjs
3911const { Buffer } = require('node:buffer');
3912
3913const buf = Buffer.alloc(256);
3914
3915const len = buf.write('\u00bd + \u00bc = \u00be', 0);
3916
3917console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
3918// Prints: 12 bytes: ½ + ¼ = ¾
3919
3920const buffer = Buffer.alloc(10);
3921
3922const length = buffer.write('abcd', 8);
3923
3924console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
3925// Prints: 2 bytes : ab
3926```
3927
3928### `buf.writeBigInt64BE(value[, offset])`
3929
3930<!-- YAML
3931added:
3932 - v12.0.0
3933 - v10.20.0
3934-->
3935
3936* `value` {bigint} Number to be written to `buf`.
3937* `offset` {integer} Number of bytes to skip before starting to write. Must
3938  satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
3939* Returns: {integer} `offset` plus the number of bytes written.
3940
3941Writes `value` to `buf` at the specified `offset` as big-endian.
3942
3943`value` is interpreted and written as a two's complement signed integer.
3944
3945```mjs
3946import { Buffer } from 'node:buffer';
3947
3948const buf = Buffer.allocUnsafe(8);
3949
3950buf.writeBigInt64BE(0x0102030405060708n, 0);
3951
3952console.log(buf);
3953// Prints: <Buffer 01 02 03 04 05 06 07 08>
3954```
3955
3956```cjs
3957const { Buffer } = require('node:buffer');
3958
3959const buf = Buffer.allocUnsafe(8);
3960
3961buf.writeBigInt64BE(0x0102030405060708n, 0);
3962
3963console.log(buf);
3964// Prints: <Buffer 01 02 03 04 05 06 07 08>
3965```
3966
3967### `buf.writeBigInt64LE(value[, offset])`
3968
3969<!-- YAML
3970added:
3971 - v12.0.0
3972 - v10.20.0
3973-->
3974
3975* `value` {bigint} Number to be written to `buf`.
3976* `offset` {integer} Number of bytes to skip before starting to write. Must
3977  satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
3978* Returns: {integer} `offset` plus the number of bytes written.
3979
3980Writes `value` to `buf` at the specified `offset` as little-endian.
3981
3982`value` is interpreted and written as a two's complement signed integer.
3983
3984```mjs
3985import { Buffer } from 'node:buffer';
3986
3987const buf = Buffer.allocUnsafe(8);
3988
3989buf.writeBigInt64LE(0x0102030405060708n, 0);
3990
3991console.log(buf);
3992// Prints: <Buffer 08 07 06 05 04 03 02 01>
3993```
3994
3995```cjs
3996const { Buffer } = require('node:buffer');
3997
3998const buf = Buffer.allocUnsafe(8);
3999
4000buf.writeBigInt64LE(0x0102030405060708n, 0);
4001
4002console.log(buf);
4003// Prints: <Buffer 08 07 06 05 04 03 02 01>
4004```
4005
4006### `buf.writeBigUInt64BE(value[, offset])`
4007
4008<!-- YAML
4009added:
4010 - v12.0.0
4011 - v10.20.0
4012changes:
4013  - version:
4014    - v14.10.0
4015    - v12.19.0
4016    pr-url: https://github.com/nodejs/node/pull/34960
4017    description: This function is also available as `buf.writeBigUint64BE()`.
4018-->
4019
4020* `value` {bigint} Number to be written to `buf`.
4021* `offset` {integer} Number of bytes to skip before starting to write. Must
4022  satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
4023* Returns: {integer} `offset` plus the number of bytes written.
4024
4025Writes `value` to `buf` at the specified `offset` as big-endian.
4026
4027This function is also available under the `writeBigUint64BE` alias.
4028
4029```mjs
4030import { Buffer } from 'node:buffer';
4031
4032const buf = Buffer.allocUnsafe(8);
4033
4034buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
4035
4036console.log(buf);
4037// Prints: <Buffer de ca fa fe ca ce fa de>
4038```
4039
4040```cjs
4041const { Buffer } = require('node:buffer');
4042
4043const buf = Buffer.allocUnsafe(8);
4044
4045buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
4046
4047console.log(buf);
4048// Prints: <Buffer de ca fa fe ca ce fa de>
4049```
4050
4051### `buf.writeBigUInt64LE(value[, offset])`
4052
4053<!-- YAML
4054added:
4055 - v12.0.0
4056 - v10.20.0
4057changes:
4058  - version:
4059    - v14.10.0
4060    - v12.19.0
4061    pr-url: https://github.com/nodejs/node/pull/34960
4062    description: This function is also available as `buf.writeBigUint64LE()`.
4063-->
4064
4065* `value` {bigint} Number to be written to `buf`.
4066* `offset` {integer} Number of bytes to skip before starting to write. Must
4067  satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
4068* Returns: {integer} `offset` plus the number of bytes written.
4069
4070Writes `value` to `buf` at the specified `offset` as little-endian
4071
4072```mjs
4073import { Buffer } from 'node:buffer';
4074
4075const buf = Buffer.allocUnsafe(8);
4076
4077buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
4078
4079console.log(buf);
4080// Prints: <Buffer de fa ce ca fe fa ca de>
4081```
4082
4083```cjs
4084const { Buffer } = require('node:buffer');
4085
4086const buf = Buffer.allocUnsafe(8);
4087
4088buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
4089
4090console.log(buf);
4091// Prints: <Buffer de fa ce ca fe fa ca de>
4092```
4093
4094This function is also available under the `writeBigUint64LE` alias.
4095
4096### `buf.writeDoubleBE(value[, offset])`
4097
4098<!-- YAML
4099added: v0.11.15
4100changes:
4101  - version: v10.0.0
4102    pr-url: https://github.com/nodejs/node/pull/18395
4103    description: Removed `noAssert` and no implicit coercion of the offset
4104                 to `uint32` anymore.
4105-->
4106
4107* `value` {number} Number to be written to `buf`.
4108* `offset` {integer} Number of bytes to skip before starting to write. Must
4109  satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
4110* Returns: {integer} `offset` plus the number of bytes written.
4111
4112Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
4113must be a JavaScript number. Behavior is undefined when `value` is anything
4114other than a JavaScript number.
4115
4116```mjs
4117import { Buffer } from 'node:buffer';
4118
4119const buf = Buffer.allocUnsafe(8);
4120
4121buf.writeDoubleBE(123.456, 0);
4122
4123console.log(buf);
4124// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>
4125```
4126
4127```cjs
4128const { Buffer } = require('node:buffer');
4129
4130const buf = Buffer.allocUnsafe(8);
4131
4132buf.writeDoubleBE(123.456, 0);
4133
4134console.log(buf);
4135// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>
4136```
4137
4138### `buf.writeDoubleLE(value[, offset])`
4139
4140<!-- YAML
4141added: v0.11.15
4142changes:
4143  - version: v10.0.0
4144    pr-url: https://github.com/nodejs/node/pull/18395
4145    description: Removed `noAssert` and no implicit coercion of the offset
4146                 to `uint32` anymore.
4147-->
4148
4149* `value` {number} Number to be written to `buf`.
4150* `offset` {integer} Number of bytes to skip before starting to write. Must
4151  satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
4152* Returns: {integer} `offset` plus the number of bytes written.
4153
4154Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
4155must be a JavaScript number. Behavior is undefined when `value` is anything
4156other than a JavaScript number.
4157
4158```mjs
4159import { Buffer } from 'node:buffer';
4160
4161const buf = Buffer.allocUnsafe(8);
4162
4163buf.writeDoubleLE(123.456, 0);
4164
4165console.log(buf);
4166// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>
4167```
4168
4169```cjs
4170const { Buffer } = require('node:buffer');
4171
4172const buf = Buffer.allocUnsafe(8);
4173
4174buf.writeDoubleLE(123.456, 0);
4175
4176console.log(buf);
4177// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>
4178```
4179
4180### `buf.writeFloatBE(value[, offset])`
4181
4182<!-- YAML
4183added: v0.11.15
4184changes:
4185  - version: v10.0.0
4186    pr-url: https://github.com/nodejs/node/pull/18395
4187    description: Removed `noAssert` and no implicit coercion of the offset
4188                 to `uint32` anymore.
4189-->
4190
4191* `value` {number} Number to be written to `buf`.
4192* `offset` {integer} Number of bytes to skip before starting to write. Must
4193  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
4194* Returns: {integer} `offset` plus the number of bytes written.
4195
4196Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is
4197undefined when `value` is anything other than a JavaScript number.
4198
4199```mjs
4200import { Buffer } from 'node:buffer';
4201
4202const buf = Buffer.allocUnsafe(4);
4203
4204buf.writeFloatBE(0xcafebabe, 0);
4205
4206console.log(buf);
4207// Prints: <Buffer 4f 4a fe bb>
4208```
4209
4210```cjs
4211const { Buffer } = require('node:buffer');
4212
4213const buf = Buffer.allocUnsafe(4);
4214
4215buf.writeFloatBE(0xcafebabe, 0);
4216
4217console.log(buf);
4218// Prints: <Buffer 4f 4a fe bb>
4219```
4220
4221### `buf.writeFloatLE(value[, offset])`
4222
4223<!-- YAML
4224added: v0.11.15
4225changes:
4226  - version: v10.0.0
4227    pr-url: https://github.com/nodejs/node/pull/18395
4228    description: Removed `noAssert` and no implicit coercion of the offset
4229                 to `uint32` anymore.
4230-->
4231
4232* `value` {number} Number to be written to `buf`.
4233* `offset` {integer} Number of bytes to skip before starting to write. Must
4234  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
4235* Returns: {integer} `offset` plus the number of bytes written.
4236
4237Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is
4238undefined when `value` is anything other than a JavaScript number.
4239
4240```mjs
4241import { Buffer } from 'node:buffer';
4242
4243const buf = Buffer.allocUnsafe(4);
4244
4245buf.writeFloatLE(0xcafebabe, 0);
4246
4247console.log(buf);
4248// Prints: <Buffer bb fe 4a 4f>
4249```
4250
4251```cjs
4252const { Buffer } = require('node:buffer');
4253
4254const buf = Buffer.allocUnsafe(4);
4255
4256buf.writeFloatLE(0xcafebabe, 0);
4257
4258console.log(buf);
4259// Prints: <Buffer bb fe 4a 4f>
4260```
4261
4262### `buf.writeInt8(value[, offset])`
4263
4264<!-- YAML
4265added: v0.5.0
4266changes:
4267  - version: v10.0.0
4268    pr-url: https://github.com/nodejs/node/pull/18395
4269    description: Removed `noAssert` and no implicit coercion of the offset
4270                 to `uint32` anymore.
4271-->
4272
4273* `value` {integer} Number to be written to `buf`.
4274* `offset` {integer} Number of bytes to skip before starting to write. Must
4275  satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
4276* Returns: {integer} `offset` plus the number of bytes written.
4277
4278Writes `value` to `buf` at the specified `offset`. `value` must be a valid
4279signed 8-bit integer. Behavior is undefined when `value` is anything other than
4280a signed 8-bit integer.
4281
4282`value` is interpreted and written as a two's complement signed integer.
4283
4284```mjs
4285import { Buffer } from 'node:buffer';
4286
4287const buf = Buffer.allocUnsafe(2);
4288
4289buf.writeInt8(2, 0);
4290buf.writeInt8(-2, 1);
4291
4292console.log(buf);
4293// Prints: <Buffer 02 fe>
4294```
4295
4296```cjs
4297const { Buffer } = require('node:buffer');
4298
4299const buf = Buffer.allocUnsafe(2);
4300
4301buf.writeInt8(2, 0);
4302buf.writeInt8(-2, 1);
4303
4304console.log(buf);
4305// Prints: <Buffer 02 fe>
4306```
4307
4308### `buf.writeInt16BE(value[, offset])`
4309
4310<!-- YAML
4311added: v0.5.5
4312changes:
4313  - version: v10.0.0
4314    pr-url: https://github.com/nodejs/node/pull/18395
4315    description: Removed `noAssert` and no implicit coercion of the offset
4316                 to `uint32` anymore.
4317-->
4318
4319* `value` {integer} Number to be written to `buf`.
4320* `offset` {integer} Number of bytes to skip before starting to write. Must
4321  satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
4322* Returns: {integer} `offset` plus the number of bytes written.
4323
4324Writes `value` to `buf` at the specified `offset` as big-endian.  The `value`
4325must be a valid signed 16-bit integer. Behavior is undefined when `value` is
4326anything other than a signed 16-bit integer.
4327
4328The `value` is interpreted and written as a two's complement signed integer.
4329
4330```mjs
4331import { Buffer } from 'node:buffer';
4332
4333const buf = Buffer.allocUnsafe(2);
4334
4335buf.writeInt16BE(0x0102, 0);
4336
4337console.log(buf);
4338// Prints: <Buffer 01 02>
4339```
4340
4341```cjs
4342const { Buffer } = require('node:buffer');
4343
4344const buf = Buffer.allocUnsafe(2);
4345
4346buf.writeInt16BE(0x0102, 0);
4347
4348console.log(buf);
4349// Prints: <Buffer 01 02>
4350```
4351
4352### `buf.writeInt16LE(value[, offset])`
4353
4354<!-- YAML
4355added: v0.5.5
4356changes:
4357  - version: v10.0.0
4358    pr-url: https://github.com/nodejs/node/pull/18395
4359    description: Removed `noAssert` and no implicit coercion of the offset
4360                 to `uint32` anymore.
4361-->
4362
4363* `value` {integer} Number to be written to `buf`.
4364* `offset` {integer} Number of bytes to skip before starting to write. Must
4365  satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
4366* Returns: {integer} `offset` plus the number of bytes written.
4367
4368Writes `value` to `buf` at the specified `offset` as little-endian.  The `value`
4369must be a valid signed 16-bit integer. Behavior is undefined when `value` is
4370anything other than a signed 16-bit integer.
4371
4372The `value` is interpreted and written as a two's complement signed integer.
4373
4374```mjs
4375import { Buffer } from 'node:buffer';
4376
4377const buf = Buffer.allocUnsafe(2);
4378
4379buf.writeInt16LE(0x0304, 0);
4380
4381console.log(buf);
4382// Prints: <Buffer 04 03>
4383```
4384
4385```cjs
4386const { Buffer } = require('node:buffer');
4387
4388const buf = Buffer.allocUnsafe(2);
4389
4390buf.writeInt16LE(0x0304, 0);
4391
4392console.log(buf);
4393// Prints: <Buffer 04 03>
4394```
4395
4396### `buf.writeInt32BE(value[, offset])`
4397
4398<!-- YAML
4399added: v0.5.5
4400changes:
4401  - version: v10.0.0
4402    pr-url: https://github.com/nodejs/node/pull/18395
4403    description: Removed `noAssert` and no implicit coercion of the offset
4404                 to `uint32` anymore.
4405-->
4406
4407* `value` {integer} Number to be written to `buf`.
4408* `offset` {integer} Number of bytes to skip before starting to write. Must
4409  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
4410* Returns: {integer} `offset` plus the number of bytes written.
4411
4412Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
4413must be a valid signed 32-bit integer. Behavior is undefined when `value` is
4414anything other than a signed 32-bit integer.
4415
4416The `value` is interpreted and written as a two's complement signed integer.
4417
4418```mjs
4419import { Buffer } from 'node:buffer';
4420
4421const buf = Buffer.allocUnsafe(4);
4422
4423buf.writeInt32BE(0x01020304, 0);
4424
4425console.log(buf);
4426// Prints: <Buffer 01 02 03 04>
4427```
4428
4429```cjs
4430const { Buffer } = require('node:buffer');
4431
4432const buf = Buffer.allocUnsafe(4);
4433
4434buf.writeInt32BE(0x01020304, 0);
4435
4436console.log(buf);
4437// Prints: <Buffer 01 02 03 04>
4438```
4439
4440### `buf.writeInt32LE(value[, offset])`
4441
4442<!-- YAML
4443added: v0.5.5
4444changes:
4445  - version: v10.0.0
4446    pr-url: https://github.com/nodejs/node/pull/18395
4447    description: Removed `noAssert` and no implicit coercion of the offset
4448                 to `uint32` anymore.
4449-->
4450
4451* `value` {integer} Number to be written to `buf`.
4452* `offset` {integer} Number of bytes to skip before starting to write. Must
4453  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
4454* Returns: {integer} `offset` plus the number of bytes written.
4455
4456Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
4457must be a valid signed 32-bit integer. Behavior is undefined when `value` is
4458anything other than a signed 32-bit integer.
4459
4460The `value` is interpreted and written as a two's complement signed integer.
4461
4462```mjs
4463import { Buffer } from 'node:buffer';
4464
4465const buf = Buffer.allocUnsafe(4);
4466
4467buf.writeInt32LE(0x05060708, 0);
4468
4469console.log(buf);
4470// Prints: <Buffer 08 07 06 05>
4471```
4472
4473```cjs
4474const { Buffer } = require('node:buffer');
4475
4476const buf = Buffer.allocUnsafe(4);
4477
4478buf.writeInt32LE(0x05060708, 0);
4479
4480console.log(buf);
4481// Prints: <Buffer 08 07 06 05>
4482```
4483
4484### `buf.writeIntBE(value, offset, byteLength)`
4485
4486<!-- YAML
4487added: v0.11.15
4488changes:
4489  - version: v10.0.0
4490    pr-url: https://github.com/nodejs/node/pull/18395
4491    description: Removed `noAssert` and no implicit coercion of the offset
4492                 and `byteLength` to `uint32` anymore.
4493-->
4494
4495* `value` {integer} Number to be written to `buf`.
4496* `offset` {integer} Number of bytes to skip before starting to write. Must
4497  satisfy `0 <= offset <= buf.length - byteLength`.
4498* `byteLength` {integer} Number of bytes to write. Must satisfy
4499  `0 < byteLength <= 6`.
4500* Returns: {integer} `offset` plus the number of bytes written.
4501
4502Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
4503as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when
4504`value` is anything other than a signed integer.
4505
4506```mjs
4507import { Buffer } from 'node:buffer';
4508
4509const buf = Buffer.allocUnsafe(6);
4510
4511buf.writeIntBE(0x1234567890ab, 0, 6);
4512
4513console.log(buf);
4514// Prints: <Buffer 12 34 56 78 90 ab>
4515```
4516
4517```cjs
4518const { Buffer } = require('node:buffer');
4519
4520const buf = Buffer.allocUnsafe(6);
4521
4522buf.writeIntBE(0x1234567890ab, 0, 6);
4523
4524console.log(buf);
4525// Prints: <Buffer 12 34 56 78 90 ab>
4526```
4527
4528### `buf.writeIntLE(value, offset, byteLength)`
4529
4530<!-- YAML
4531added: v0.11.15
4532changes:
4533  - version: v10.0.0
4534    pr-url: https://github.com/nodejs/node/pull/18395
4535    description: Removed `noAssert` and no implicit coercion of the offset
4536                 and `byteLength` to `uint32` anymore.
4537-->
4538
4539* `value` {integer} Number to be written to `buf`.
4540* `offset` {integer} Number of bytes to skip before starting to write. Must
4541  satisfy `0 <= offset <= buf.length - byteLength`.
4542* `byteLength` {integer} Number of bytes to write. Must satisfy
4543  `0 < byteLength <= 6`.
4544* Returns: {integer} `offset` plus the number of bytes written.
4545
4546Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
4547as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
4548when `value` is anything other than a signed integer.
4549
4550```mjs
4551import { Buffer } from 'node:buffer';
4552
4553const buf = Buffer.allocUnsafe(6);
4554
4555buf.writeIntLE(0x1234567890ab, 0, 6);
4556
4557console.log(buf);
4558// Prints: <Buffer ab 90 78 56 34 12>
4559```
4560
4561```cjs
4562const { Buffer } = require('node:buffer');
4563
4564const buf = Buffer.allocUnsafe(6);
4565
4566buf.writeIntLE(0x1234567890ab, 0, 6);
4567
4568console.log(buf);
4569// Prints: <Buffer ab 90 78 56 34 12>
4570```
4571
4572### `buf.writeUInt8(value[, offset])`
4573
4574<!-- YAML
4575added: v0.5.0
4576changes:
4577  - version:
4578    - v14.9.0
4579    - v12.19.0
4580    pr-url: https://github.com/nodejs/node/pull/34729
4581    description: This function is also available as `buf.writeUint8()`.
4582  - version: v10.0.0
4583    pr-url: https://github.com/nodejs/node/pull/18395
4584    description: Removed `noAssert` and no implicit coercion of the offset
4585                 to `uint32` anymore.
4586-->
4587
4588* `value` {integer} Number to be written to `buf`.
4589* `offset` {integer} Number of bytes to skip before starting to write. Must
4590  satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
4591* Returns: {integer} `offset` plus the number of bytes written.
4592
4593Writes `value` to `buf` at the specified `offset`. `value` must be a
4594valid unsigned 8-bit integer. Behavior is undefined when `value` is anything
4595other than an unsigned 8-bit integer.
4596
4597This function is also available under the `writeUint8` alias.
4598
4599```mjs
4600import { Buffer } from 'node:buffer';
4601
4602const buf = Buffer.allocUnsafe(4);
4603
4604buf.writeUInt8(0x3, 0);
4605buf.writeUInt8(0x4, 1);
4606buf.writeUInt8(0x23, 2);
4607buf.writeUInt8(0x42, 3);
4608
4609console.log(buf);
4610// Prints: <Buffer 03 04 23 42>
4611```
4612
4613```cjs
4614const { Buffer } = require('node:buffer');
4615
4616const buf = Buffer.allocUnsafe(4);
4617
4618buf.writeUInt8(0x3, 0);
4619buf.writeUInt8(0x4, 1);
4620buf.writeUInt8(0x23, 2);
4621buf.writeUInt8(0x42, 3);
4622
4623console.log(buf);
4624// Prints: <Buffer 03 04 23 42>
4625```
4626
4627### `buf.writeUInt16BE(value[, offset])`
4628
4629<!-- YAML
4630added: v0.5.5
4631changes:
4632  - version:
4633    - v14.9.0
4634    - v12.19.0
4635    pr-url: https://github.com/nodejs/node/pull/34729
4636    description: This function is also available as `buf.writeUint16BE()`.
4637  - version: v10.0.0
4638    pr-url: https://github.com/nodejs/node/pull/18395
4639    description: Removed `noAssert` and no implicit coercion of the offset
4640                 to `uint32` anymore.
4641-->
4642
4643* `value` {integer} Number to be written to `buf`.
4644* `offset` {integer} Number of bytes to skip before starting to write. Must
4645  satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
4646* Returns: {integer} `offset` plus the number of bytes written.
4647
4648Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
4649must be a valid unsigned 16-bit integer. Behavior is undefined when `value`
4650is anything other than an unsigned 16-bit integer.
4651
4652This function is also available under the `writeUint16BE` alias.
4653
4654```mjs
4655import { Buffer } from 'node:buffer';
4656
4657const buf = Buffer.allocUnsafe(4);
4658
4659buf.writeUInt16BE(0xdead, 0);
4660buf.writeUInt16BE(0xbeef, 2);
4661
4662console.log(buf);
4663// Prints: <Buffer de ad be ef>
4664```
4665
4666```cjs
4667const { Buffer } = require('node:buffer');
4668
4669const buf = Buffer.allocUnsafe(4);
4670
4671buf.writeUInt16BE(0xdead, 0);
4672buf.writeUInt16BE(0xbeef, 2);
4673
4674console.log(buf);
4675// Prints: <Buffer de ad be ef>
4676```
4677
4678### `buf.writeUInt16LE(value[, offset])`
4679
4680<!-- YAML
4681added: v0.5.5
4682changes:
4683  - version:
4684    - v14.9.0
4685    - v12.19.0
4686    pr-url: https://github.com/nodejs/node/pull/34729
4687    description: This function is also available as `buf.writeUint16LE()`.
4688  - version: v10.0.0
4689    pr-url: https://github.com/nodejs/node/pull/18395
4690    description: Removed `noAssert` and no implicit coercion of the offset
4691                 to `uint32` anymore.
4692-->
4693
4694* `value` {integer} Number to be written to `buf`.
4695* `offset` {integer} Number of bytes to skip before starting to write. Must
4696  satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
4697* Returns: {integer} `offset` plus the number of bytes written.
4698
4699Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
4700must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is
4701anything other than an unsigned 16-bit integer.
4702
4703This function is also available under the `writeUint16LE` alias.
4704
4705```mjs
4706import { Buffer } from 'node:buffer';
4707
4708const buf = Buffer.allocUnsafe(4);
4709
4710buf.writeUInt16LE(0xdead, 0);
4711buf.writeUInt16LE(0xbeef, 2);
4712
4713console.log(buf);
4714// Prints: <Buffer ad de ef be>
4715```
4716
4717```cjs
4718const { Buffer } = require('node:buffer');
4719
4720const buf = Buffer.allocUnsafe(4);
4721
4722buf.writeUInt16LE(0xdead, 0);
4723buf.writeUInt16LE(0xbeef, 2);
4724
4725console.log(buf);
4726// Prints: <Buffer ad de ef be>
4727```
4728
4729### `buf.writeUInt32BE(value[, offset])`
4730
4731<!-- YAML
4732added: v0.5.5
4733changes:
4734  - version:
4735    - v14.9.0
4736    - v12.19.0
4737    pr-url: https://github.com/nodejs/node/pull/34729
4738    description: This function is also available as `buf.writeUint32BE()`.
4739  - version: v10.0.0
4740    pr-url: https://github.com/nodejs/node/pull/18395
4741    description: Removed `noAssert` and no implicit coercion of the offset
4742                 to `uint32` anymore.
4743-->
4744
4745* `value` {integer} Number to be written to `buf`.
4746* `offset` {integer} Number of bytes to skip before starting to write. Must
4747  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
4748* Returns: {integer} `offset` plus the number of bytes written.
4749
4750Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
4751must be a valid unsigned 32-bit integer. Behavior is undefined when `value`
4752is anything other than an unsigned 32-bit integer.
4753
4754This function is also available under the `writeUint32BE` alias.
4755
4756```mjs
4757import { Buffer } from 'node:buffer';
4758
4759const buf = Buffer.allocUnsafe(4);
4760
4761buf.writeUInt32BE(0xfeedface, 0);
4762
4763console.log(buf);
4764// Prints: <Buffer fe ed fa ce>
4765```
4766
4767```cjs
4768const { Buffer } = require('node:buffer');
4769
4770const buf = Buffer.allocUnsafe(4);
4771
4772buf.writeUInt32BE(0xfeedface, 0);
4773
4774console.log(buf);
4775// Prints: <Buffer fe ed fa ce>
4776```
4777
4778### `buf.writeUInt32LE(value[, offset])`
4779
4780<!-- YAML
4781added: v0.5.5
4782changes:
4783  - version:
4784    - v14.9.0
4785    - v12.19.0
4786    pr-url: https://github.com/nodejs/node/pull/34729
4787    description: This function is also available as `buf.writeUint32LE()`.
4788  - version: v10.0.0
4789    pr-url: https://github.com/nodejs/node/pull/18395
4790    description: Removed `noAssert` and no implicit coercion of the offset
4791                 to `uint32` anymore.
4792-->
4793
4794* `value` {integer} Number to be written to `buf`.
4795* `offset` {integer} Number of bytes to skip before starting to write. Must
4796  satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
4797* Returns: {integer} `offset` plus the number of bytes written.
4798
4799Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
4800must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is
4801anything other than an unsigned 32-bit integer.
4802
4803This function is also available under the `writeUint32LE` alias.
4804
4805```mjs
4806import { Buffer } from 'node:buffer';
4807
4808const buf = Buffer.allocUnsafe(4);
4809
4810buf.writeUInt32LE(0xfeedface, 0);
4811
4812console.log(buf);
4813// Prints: <Buffer ce fa ed fe>
4814```
4815
4816```cjs
4817const { Buffer } = require('node:buffer');
4818
4819const buf = Buffer.allocUnsafe(4);
4820
4821buf.writeUInt32LE(0xfeedface, 0);
4822
4823console.log(buf);
4824// Prints: <Buffer ce fa ed fe>
4825```
4826
4827### `buf.writeUIntBE(value, offset, byteLength)`
4828
4829<!-- YAML
4830added: v0.5.5
4831changes:
4832  - version:
4833    - v14.9.0
4834    - v12.19.0
4835    pr-url: https://github.com/nodejs/node/pull/34729
4836    description: This function is also available as `buf.writeUintBE()`.
4837  - version: v10.0.0
4838    pr-url: https://github.com/nodejs/node/pull/18395
4839    description: Removed `noAssert` and no implicit coercion of the offset
4840                 and `byteLength` to `uint32` anymore.
4841-->
4842
4843* `value` {integer} Number to be written to `buf`.
4844* `offset` {integer} Number of bytes to skip before starting to write. Must
4845  satisfy `0 <= offset <= buf.length - byteLength`.
4846* `byteLength` {integer} Number of bytes to write. Must satisfy
4847  `0 < byteLength <= 6`.
4848* Returns: {integer} `offset` plus the number of bytes written.
4849
4850Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
4851as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined
4852when `value` is anything other than an unsigned integer.
4853
4854This function is also available under the `writeUintBE` alias.
4855
4856```mjs
4857import { Buffer } from 'node:buffer';
4858
4859const buf = Buffer.allocUnsafe(6);
4860
4861buf.writeUIntBE(0x1234567890ab, 0, 6);
4862
4863console.log(buf);
4864// Prints: <Buffer 12 34 56 78 90 ab>
4865```
4866
4867```cjs
4868const { Buffer } = require('node:buffer');
4869
4870const buf = Buffer.allocUnsafe(6);
4871
4872buf.writeUIntBE(0x1234567890ab, 0, 6);
4873
4874console.log(buf);
4875// Prints: <Buffer 12 34 56 78 90 ab>
4876```
4877
4878### `buf.writeUIntLE(value, offset, byteLength)`
4879
4880<!-- YAML
4881added: v0.5.5
4882changes:
4883  - version:
4884    - v14.9.0
4885    - v12.19.0
4886    pr-url: https://github.com/nodejs/node/pull/34729
4887    description: This function is also available as `buf.writeUintLE()`.
4888  - version: v10.0.0
4889    pr-url: https://github.com/nodejs/node/pull/18395
4890    description: Removed `noAssert` and no implicit coercion of the offset
4891                 and `byteLength` to `uint32` anymore.
4892-->
4893
4894* `value` {integer} Number to be written to `buf`.
4895* `offset` {integer} Number of bytes to skip before starting to write. Must
4896  satisfy `0 <= offset <= buf.length - byteLength`.
4897* `byteLength` {integer} Number of bytes to write. Must satisfy
4898  `0 < byteLength <= 6`.
4899* Returns: {integer} `offset` plus the number of bytes written.
4900
4901Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
4902as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
4903when `value` is anything other than an unsigned integer.
4904
4905This function is also available under the `writeUintLE` alias.
4906
4907```mjs
4908import { Buffer } from 'node:buffer';
4909
4910const buf = Buffer.allocUnsafe(6);
4911
4912buf.writeUIntLE(0x1234567890ab, 0, 6);
4913
4914console.log(buf);
4915// Prints: <Buffer ab 90 78 56 34 12>
4916```
4917
4918```cjs
4919const { Buffer } = require('node:buffer');
4920
4921const buf = Buffer.allocUnsafe(6);
4922
4923buf.writeUIntLE(0x1234567890ab, 0, 6);
4924
4925console.log(buf);
4926// Prints: <Buffer ab 90 78 56 34 12>
4927```
4928
4929### `new Buffer(array)`
4930
4931<!-- YAML
4932deprecated: v6.0.0
4933changes:
4934  - version: v10.0.0
4935    pr-url: https://github.com/nodejs/node/pull/19524
4936    description: Calling this constructor emits a deprecation warning when
4937                 run from code outside the `node_modules` directory.
4938  - version: v7.2.1
4939    pr-url: https://github.com/nodejs/node/pull/9529
4940    description: Calling this constructor no longer emits a deprecation warning.
4941  - version: v7.0.0
4942    pr-url: https://github.com/nodejs/node/pull/8169
4943    description: Calling this constructor emits a deprecation warning now.
4944-->
4945
4946> Stability: 0 - Deprecated: Use [`Buffer.from(array)`][] instead.
4947
4948* `array` {integer\[]} An array of bytes to copy from.
4949
4950See [`Buffer.from(array)`][].
4951
4952### `new Buffer(arrayBuffer[, byteOffset[, length]])`
4953
4954<!-- YAML
4955added: v3.0.0
4956deprecated: v6.0.0
4957changes:
4958  - version: v10.0.0
4959    pr-url: https://github.com/nodejs/node/pull/19524
4960    description: Calling this constructor emits a deprecation warning when
4961                 run from code outside the `node_modules` directory.
4962  - version: v7.2.1
4963    pr-url: https://github.com/nodejs/node/pull/9529
4964    description: Calling this constructor no longer emits a deprecation warning.
4965  - version: v7.0.0
4966    pr-url: https://github.com/nodejs/node/pull/8169
4967    description: Calling this constructor emits a deprecation warning now.
4968  - version: v6.0.0
4969    pr-url: https://github.com/nodejs/node/pull/4682
4970    description: The `byteOffset` and `length` parameters are supported now.
4971-->
4972
4973> Stability: 0 - Deprecated: Use
4974> [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
4975> instead.
4976
4977* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][],
4978  [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][].
4979* `byteOffset` {integer} Index of first byte to expose. **Default:** `0`.
4980* `length` {integer} Number of bytes to expose.
4981  **Default:** `arrayBuffer.byteLength - byteOffset`.
4982
4983See
4984[`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`].
4985
4986### `new Buffer(buffer)`
4987
4988<!-- YAML
4989deprecated: v6.0.0
4990changes:
4991  - version: v10.0.0
4992    pr-url: https://github.com/nodejs/node/pull/19524
4993    description: Calling this constructor emits a deprecation warning when
4994                 run from code outside the `node_modules` directory.
4995  - version: v7.2.1
4996    pr-url: https://github.com/nodejs/node/pull/9529
4997    description: Calling this constructor no longer emits a deprecation warning.
4998  - version: v7.0.0
4999    pr-url: https://github.com/nodejs/node/pull/8169
5000    description: Calling this constructor emits a deprecation warning now.
5001-->
5002
5003> Stability: 0 - Deprecated: Use [`Buffer.from(buffer)`][] instead.
5004
5005* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from
5006  which to copy data.
5007
5008See [`Buffer.from(buffer)`][].
5009
5010### `new Buffer(size)`
5011
5012<!-- YAML
5013deprecated: v6.0.0
5014changes:
5015  - version: v10.0.0
5016    pr-url: https://github.com/nodejs/node/pull/19524
5017    description: Calling this constructor emits a deprecation warning when
5018                 run from code outside the `node_modules` directory.
5019  - version: v8.0.0
5020    pr-url: https://github.com/nodejs/node/pull/12141
5021    description: The `new Buffer(size)` will return zero-filled memory by
5022                 default.
5023  - version: v7.2.1
5024    pr-url: https://github.com/nodejs/node/pull/9529
5025    description: Calling this constructor no longer emits a deprecation warning.
5026  - version: v7.0.0
5027    pr-url: https://github.com/nodejs/node/pull/8169
5028    description: Calling this constructor emits a deprecation warning now.
5029-->
5030
5031> Stability: 0 - Deprecated: Use [`Buffer.alloc()`][] instead (also see
5032> [`Buffer.allocUnsafe()`][]).
5033
5034* `size` {integer} The desired length of the new `Buffer`.
5035
5036See [`Buffer.alloc()`][] and [`Buffer.allocUnsafe()`][]. This variant of the
5037constructor is equivalent to [`Buffer.alloc()`][].
5038
5039### `new Buffer(string[, encoding])`
5040
5041<!-- YAML
5042deprecated: v6.0.0
5043changes:
5044  - version: v10.0.0
5045    pr-url: https://github.com/nodejs/node/pull/19524
5046    description: Calling this constructor emits a deprecation warning when
5047                 run from code outside the `node_modules` directory.
5048  - version: v7.2.1
5049    pr-url: https://github.com/nodejs/node/pull/9529
5050    description: Calling this constructor no longer emits a deprecation warning.
5051  - version: v7.0.0
5052    pr-url: https://github.com/nodejs/node/pull/8169
5053    description: Calling this constructor emits a deprecation warning now.
5054-->
5055
5056> Stability: 0 - Deprecated:
5057> Use [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] instead.
5058
5059* `string` {string} String to encode.
5060* `encoding` {string} The encoding of `string`. **Default:** `'utf8'`.
5061
5062See [`Buffer.from(string[, encoding])`][`Buffer.from(string)`].
5063
5064## Class: `File`
5065
5066<!-- YAML
5067added: v18.13.0
5068-->
5069
5070> Stability: 1 - Experimental
5071
5072* Extends: {Blob}
5073
5074A [`File`][] provides information about files.
5075
5076### `new buffer.File(sources, fileName[, options])`
5077
5078<!-- YAML
5079added: v18.13.0
5080-->
5081
5082* `sources` {string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[]|File\[]}
5083  An array of string, {ArrayBuffer}, {TypedArray}, {DataView}, {File}, or {Blob}
5084  objects, or any mix of such objects, that will be stored within the `File`.
5085* `fileName` {string} The name of the file.
5086* `options` {Object}
5087  * `endings` {string} One of either `'transparent'` or `'native'`. When set
5088    to `'native'`, line endings in string source parts will be converted to
5089    the platform native line-ending as specified by `require('node:os').EOL`.
5090  * `type` {string} The File content-type.
5091  * `lastModified` {number} The last modified date of the file.
5092    **Default:** `Date.now()`.
5093
5094### `file.name`
5095
5096<!-- YAML
5097added: v18.13.0
5098-->
5099
5100* Type: {string}
5101
5102The name of the `File`.
5103
5104### `file.lastModified`
5105
5106<!-- YAML
5107added: v18.13.0
5108-->
5109
5110* Type: {number}
5111
5112The last modified date of the `File`.
5113
5114## `node:buffer` module APIs
5115
5116While, the `Buffer` object is available as a global, there are additional
5117`Buffer`-related APIs that are available only via the `node:buffer` module
5118accessed using `require('node:buffer')`.
5119
5120### `buffer.atob(data)`
5121
5122<!-- YAML
5123added:
5124  - v15.13.0
5125  - v14.17.0
5126-->
5127
5128> Stability: 3 - Legacy. Use `Buffer.from(data, 'base64')` instead.
5129
5130* `data` {any} The Base64-encoded input string.
5131
5132Decodes a string of Base64-encoded data into bytes, and encodes those bytes
5133into a string using Latin-1 (ISO-8859-1).
5134
5135The `data` may be any JavaScript-value that can be coerced into a string.
5136
5137**This function is only provided for compatibility with legacy web platform APIs
5138and should never be used in new code, because they use strings to represent
5139binary data and predate the introduction of typed arrays in JavaScript.
5140For code running using Node.js APIs, converting between base64-encoded strings
5141and binary data should be performed using `Buffer.from(str, 'base64')` and
5142`buf.toString('base64')`.**
5143
5144### `buffer.btoa(data)`
5145
5146<!-- YAML
5147added:
5148  - v15.13.0
5149  - v14.17.0
5150-->
5151
5152> Stability: 3 - Legacy. Use `buf.toString('base64')` instead.
5153
5154* `data` {any} An ASCII (Latin1) string.
5155
5156Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes
5157into a string using Base64.
5158
5159The `data` may be any JavaScript-value that can be coerced into a string.
5160
5161**This function is only provided for compatibility with legacy web platform APIs
5162and should never be used in new code, because they use strings to represent
5163binary data and predate the introduction of typed arrays in JavaScript.
5164For code running using Node.js APIs, converting between base64-encoded strings
5165and binary data should be performed using `Buffer.from(str, 'base64')` and
5166`buf.toString('base64')`.**
5167
5168### `buffer.isAscii(input)`
5169
5170<!-- YAML
5171added: v18.15.0
5172-->
5173
5174* input {Buffer | ArrayBuffer | TypedArray} The input to validate.
5175* Returns: {boolean}
5176
5177This function returns `true` if `input` contains only valid ASCII-encoded data,
5178including the case in which `input` is empty.
5179
5180Throws if the `input` is a detached array buffer.
5181
5182### `buffer.isUtf8(input)`
5183
5184<!-- YAML
5185added: v18.14.0
5186-->
5187
5188* input {Buffer | ArrayBuffer | TypedArray} The input to validate.
5189* Returns: {boolean}
5190
5191This function returns `true` if `input` contains only valid UTF-8-encoded data,
5192including the case in which `input` is empty.
5193
5194Throws if the `input` is a detached array buffer.
5195
5196### `buffer.INSPECT_MAX_BYTES`
5197
5198<!-- YAML
5199added: v0.5.4
5200-->
5201
5202* {integer} **Default:** `50`
5203
5204Returns the maximum number of bytes that will be returned when
5205`buf.inspect()` is called. This can be overridden by user modules. See
5206[`util.inspect()`][] for more details on `buf.inspect()` behavior.
5207
5208### `buffer.kMaxLength`
5209
5210<!-- YAML
5211added: v3.0.0
5212-->
5213
5214* {integer} The largest size allowed for a single `Buffer` instance.
5215
5216An alias for [`buffer.constants.MAX_LENGTH`][].
5217
5218### `buffer.kStringMaxLength`
5219
5220<!-- YAML
5221added: v3.0.0
5222-->
5223
5224* {integer} The largest length allowed for a single `string` instance.
5225
5226An alias for [`buffer.constants.MAX_STRING_LENGTH`][].
5227
5228### `buffer.resolveObjectURL(id)`
5229
5230<!-- YAML
5231added: v16.7.0
5232-->
5233
5234> Stability: 1 - Experimental
5235
5236* `id` {string} A `'blob:nodedata:...` URL string returned by a prior call to
5237  `URL.createObjectURL()`.
5238* Returns: {Blob}
5239
5240Resolves a `'blob:nodedata:...'` an associated {Blob} object registered using
5241a prior call to `URL.createObjectURL()`.
5242
5243### `buffer.transcode(source, fromEnc, toEnc)`
5244
5245<!-- YAML
5246added: v7.1.0
5247changes:
5248  - version: v8.0.0
5249    pr-url: https://github.com/nodejs/node/pull/10236
5250    description: The `source` parameter can now be a `Uint8Array`.
5251-->
5252
5253* `source` {Buffer|Uint8Array} A `Buffer` or `Uint8Array` instance.
5254* `fromEnc` {string} The current encoding.
5255* `toEnc` {string} To target encoding.
5256* Returns: {Buffer}
5257
5258Re-encodes the given `Buffer` or `Uint8Array` instance from one character
5259encoding to another. Returns a new `Buffer` instance.
5260
5261Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if
5262conversion from `fromEnc` to `toEnc` is not permitted.
5263
5264Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,
5265`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`.
5266
5267The transcoding process will use substitution characters if a given byte
5268sequence cannot be adequately represented in the target encoding. For instance:
5269
5270```mjs
5271import { Buffer, transcode } from 'node:buffer';
5272
5273const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
5274console.log(newBuf.toString('ascii'));
5275// Prints: '?'
5276```
5277
5278```cjs
5279const { Buffer, transcode } = require('node:buffer');
5280
5281const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
5282console.log(newBuf.toString('ascii'));
5283// Prints: '?'
5284```
5285
5286Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced
5287with `?` in the transcoded `Buffer`.
5288
5289### Class: `SlowBuffer`
5290
5291<!-- YAML
5292deprecated: v6.0.0
5293-->
5294
5295> Stability: 0 - Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.
5296
5297See [`Buffer.allocUnsafeSlow()`][]. This was never a class in the sense that
5298the constructor always returned a `Buffer` instance, rather than a `SlowBuffer`
5299instance.
5300
5301#### `new SlowBuffer(size)`
5302
5303<!-- YAML
5304deprecated: v6.0.0
5305-->
5306
5307> Stability: 0 - Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.
5308
5309* `size` {integer} The desired length of the new `SlowBuffer`.
5310
5311See [`Buffer.allocUnsafeSlow()`][].
5312
5313### Buffer constants
5314
5315<!-- YAML
5316added: v8.2.0
5317-->
5318
5319#### `buffer.constants.MAX_LENGTH`
5320
5321<!-- YAML
5322added: v8.2.0
5323changes:
5324  - version: v15.0.0
5325    pr-url: https://github.com/nodejs/node/pull/35415
5326    description: Value is changed to 2<sup>32</sup> on 64-bit
5327      architectures.
5328  - version: v14.0.0
5329    pr-url: https://github.com/nodejs/node/pull/32116
5330    description: Value is changed from 2<sup>31</sup> - 1 to
5331      2<sup>32</sup> - 1 on 64-bit architectures.
5332-->
5333
5334* {integer} The largest size allowed for a single `Buffer` instance.
5335
5336On 32-bit architectures, this value currently is 2<sup>30</sup> - 1 (about 1
5337GiB).
5338
5339On 64-bit architectures, this value currently is 2<sup>32</sup> (about 4 GiB).
5340
5341It reflects [`v8::TypedArray::kMaxLength`][] under the hood.
5342
5343This value is also available as [`buffer.kMaxLength`][].
5344
5345#### `buffer.constants.MAX_STRING_LENGTH`
5346
5347<!-- YAML
5348added: v8.2.0
5349-->
5350
5351* {integer} The largest length allowed for a single `string` instance.
5352
5353Represents the largest `length` that a `string` primitive can have, counted
5354in UTF-16 code units.
5355
5356This value may depend on the JS engine that is being used.
5357
5358## `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`
5359
5360In versions of Node.js prior to 6.0.0, `Buffer` instances were created using the
5361`Buffer` constructor function, which allocates the returned `Buffer`
5362differently based on what arguments are provided:
5363
5364* Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`)
5365  allocates a new `Buffer` object of the specified size. Prior to Node.js 8.0.0,
5366  the memory allocated for such `Buffer` instances is _not_ initialized and
5367  _can contain sensitive data_. Such `Buffer` instances _must_ be subsequently
5368  initialized by using either [`buf.fill(0)`][`buf.fill()`] or by writing to the
5369  entire `Buffer` before reading data from the `Buffer`.
5370  While this behavior is _intentional_ to improve performance,
5371  development experience has demonstrated that a more explicit distinction is
5372  required between creating a fast-but-uninitialized `Buffer` versus creating a
5373  slower-but-safer `Buffer`. Since Node.js 8.0.0, `Buffer(num)` and `new
5374  Buffer(num)` return a `Buffer` with initialized memory.
5375* Passing a string, array, or `Buffer` as the first argument copies the
5376  passed object's data into the `Buffer`.
5377* Passing an [`ArrayBuffer`][] or a [`SharedArrayBuffer`][] returns a `Buffer`
5378  that shares allocated memory with the given array buffer.
5379
5380Because the behavior of `new Buffer()` is different depending on the type of the
5381first argument, security and reliability issues can be inadvertently introduced
5382into applications when argument validation or `Buffer` initialization is not
5383performed.
5384
5385For example, if an attacker can cause an application to receive a number where
5386a string is expected, the application may call `new Buffer(100)`
5387instead of `new Buffer("100")`, leading it to allocate a 100 byte buffer instead
5388of allocating a 3 byte buffer with content `"100"`. This is commonly possible
5389using JSON API calls. Since JSON distinguishes between numeric and string types,
5390it allows injection of numbers where a naively written application that does not
5391validate its input sufficiently might expect to always receive a string.
5392Before Node.js 8.0.0, the 100 byte buffer might contain
5393arbitrary pre-existing in-memory data, so may be used to expose in-memory
5394secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot
5395occur because the data is zero-filled. However, other attacks are still
5396possible, such as causing very large buffers to be allocated by the server,
5397leading to performance degradation or crashing on memory exhaustion.
5398
5399To make the creation of `Buffer` instances more reliable and less error-prone,
5400the various forms of the `new Buffer()` constructor have been **deprecated**
5401and replaced by separate `Buffer.from()`, [`Buffer.alloc()`][], and
5402[`Buffer.allocUnsafe()`][] methods.
5403
5404_Developers should migrate all existing uses of the `new Buffer()` constructors
5405to one of these new APIs._
5406
5407* [`Buffer.from(array)`][] returns a new `Buffer` that _contains a copy_ of the
5408  provided octets.
5409* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
5410  returns a new `Buffer` that _shares the same allocated memory_ as the given
5411  [`ArrayBuffer`][].
5412* [`Buffer.from(buffer)`][] returns a new `Buffer` that _contains a copy_ of the
5413  contents of the given `Buffer`.
5414* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new
5415  `Buffer` that _contains a copy_ of the provided string.
5416* [`Buffer.alloc(size[, fill[, encoding]])`][`Buffer.alloc()`] returns a new
5417  initialized `Buffer` of the specified size. This method is slower than
5418  [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] but guarantees that newly
5419  created `Buffer` instances never contain old data that is potentially
5420  sensitive. A `TypeError` will be thrown if `size` is not a number.
5421* [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] and
5422  [`Buffer.allocUnsafeSlow(size)`][`Buffer.allocUnsafeSlow()`] each return a
5423  new uninitialized `Buffer` of the specified `size`. Because the `Buffer` is
5424  uninitialized, the allocated segment of memory might contain old data that is
5425  potentially sensitive.
5426
5427`Buffer` instances returned by [`Buffer.allocUnsafe()`][] and
5428[`Buffer.from(array)`][] _may_ be allocated off a shared internal memory pool
5429if `size` is less than or equal to half [`Buffer.poolSize`][]. Instances
5430returned by [`Buffer.allocUnsafeSlow()`][] _never_ use the shared internal
5431memory pool.
5432
5433### The `--zero-fill-buffers` command-line option
5434
5435<!-- YAML
5436added: v5.10.0
5437-->
5438
5439Node.js can be started using the `--zero-fill-buffers` command-line option to
5440cause all newly-allocated `Buffer` instances to be zero-filled upon creation by
5441default. Without the option, buffers created with [`Buffer.allocUnsafe()`][],
5442[`Buffer.allocUnsafeSlow()`][], and `new SlowBuffer(size)` are not zero-filled.
5443Use of this flag can have a measurable negative impact on performance. Use the
5444`--zero-fill-buffers` option only when necessary to enforce that newly allocated
5445`Buffer` instances cannot contain old data that is potentially sensitive.
5446
5447```console
5448$ node --zero-fill-buffers
5449> Buffer.allocUnsafe(5);
5450<Buffer 00 00 00 00 00>
5451```
5452
5453### What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` "unsafe"?
5454
5455When calling [`Buffer.allocUnsafe()`][] and [`Buffer.allocUnsafeSlow()`][], the
5456segment of allocated memory is _uninitialized_ (it is not zeroed-out). While
5457this design makes the allocation of memory quite fast, the allocated segment of
5458memory might contain old data that is potentially sensitive. Using a `Buffer`
5459created by [`Buffer.allocUnsafe()`][] without _completely_ overwriting the
5460memory can allow this old data to be leaked when the `Buffer` memory is read.
5461
5462While there are clear performance advantages to using
5463[`Buffer.allocUnsafe()`][], extra care _must_ be taken in order to avoid
5464introducing security vulnerabilities into an application.
5465
5466[ASCII]: https://en.wikipedia.org/wiki/ASCII
5467[Base64]: https://en.wikipedia.org/wiki/Base64
5468[ISO-8859-1]: https://en.wikipedia.org/wiki/ISO-8859-1
5469[RFC 4648, Section 5]: https://tools.ietf.org/html/rfc4648#section-5
5470[UTF-16]: https://en.wikipedia.org/wiki/UTF-16
5471[UTF-8]: https://en.wikipedia.org/wiki/UTF-8
5472[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/
5473[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
5474[`Blob`]: https://developer.mozilla.org/en-US/docs/Web/API/Blob
5475[`Buffer.alloc()`]: #static-method-bufferallocsize-fill-encoding
5476[`Buffer.allocUnsafe()`]: #static-method-bufferallocunsafesize
5477[`Buffer.allocUnsafeSlow()`]: #static-method-bufferallocunsafeslowsize
5478[`Buffer.concat()`]: #static-method-bufferconcatlist-totallength
5479[`Buffer.copyBytesFrom()`]: #static-method-buffercopybytesfromview-offset-length
5480[`Buffer.from(array)`]: #static-method-bufferfromarray
5481[`Buffer.from(arrayBuf)`]: #static-method-bufferfromarraybuffer-byteoffset-length
5482[`Buffer.from(buffer)`]: #static-method-bufferfrombuffer
5483[`Buffer.from(string)`]: #static-method-bufferfromstring-encoding
5484[`Buffer.poolSize`]: #class-property-bufferpoolsize
5485[`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
5486[`ERR_INVALID_BUFFER_SIZE`]: errors.md#err_invalid_buffer_size
5487[`ERR_OUT_OF_RANGE`]: errors.md#err_out_of_range
5488[`File`]: https://developer.mozilla.org/en-US/docs/Web/API/File
5489[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
5490[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
5491[`String.prototype.indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
5492[`String.prototype.lastIndexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
5493[`String.prototype.length`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
5494[`TypedArray.from()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from
5495[`TypedArray.prototype.set()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set
5496[`TypedArray.prototype.slice()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice
5497[`TypedArray.prototype.subarray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray
5498[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
5499[`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
5500[`buf.buffer`]: #bufbuffer
5501[`buf.compare()`]: #bufcomparetarget-targetstart-targetend-sourcestart-sourceend
5502[`buf.entries()`]: #bufentries
5503[`buf.fill()`]: #buffillvalue-offset-end-encoding
5504[`buf.indexOf()`]: #bufindexofvalue-byteoffset-encoding
5505[`buf.keys()`]: #bufkeys
5506[`buf.length`]: #buflength
5507[`buf.slice()`]: #bufslicestart-end
5508[`buf.subarray`]: #bufsubarraystart-end
5509[`buf.toString()`]: #buftostringencoding-start-end
5510[`buf.values()`]: #bufvalues
5511[`buffer.constants.MAX_LENGTH`]: #bufferconstantsmax_length
5512[`buffer.constants.MAX_STRING_LENGTH`]: #bufferconstantsmax_string_length
5513[`buffer.kMaxLength`]: #bufferkmaxlength
5514[`util.inspect()`]: util.md#utilinspectobject-options
5515[`v8::TypedArray::kMaxLength`]: https://v8.github.io/api/head/classv8_1_1TypedArray.html#a54a48f4373da0850663c4393d843b9b0
5516[base64url]: https://tools.ietf.org/html/rfc4648#section-5
5517[endianness]: https://en.wikipedia.org/wiki/Endianness
5518[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
5519