5 Prior to the introduction of `TypedArray` in ECMAScript 2015 (ES6), the
6 JavaScript language had no mechanism for reading or manipulating streams
7 of binary data. The `Buffer` class was introduced as part of the Node.js
8 API to make it possible to interact with octet streams in the context of things
9 like TCP streams and file system operations.
11 Now that `TypedArray` has been added in ES6, the `Buffer` class implements the
12 `Uint8Array` API in a manner that is more optimized and suitable for Node.js'
15 Instances of the `Buffer` class are similar to arrays of integers but
16 correspond to fixed-sized, raw memory allocations outside the V8 heap.
17 The size of the `Buffer` is established when it is created and cannot be
20 The `Buffer` class is a global within Node.js, making it unlikely that one
21 would need to ever use `require('buffer')`.
24 const buf1 = new Buffer(10);
25 // creates a buffer of length 10
27 const buf2 = new Buffer([1,2,3]);
28 // creates a buffer containing [01, 02, 03]
30 const buf3 = new Buffer('test');
31 // creates a buffer containing ASCII bytes [74, 65, 73, 74]
33 const buf4 = new Buffer('tést', 'utf8');
34 // creates a buffer containing UTF8 bytes [74, c3, a9, 73, 74]
37 ## Buffers and Character Encodings
39 Buffers are commonly used to represent sequences of encoded characters
40 such as UTF8, UCS2, Base64 or even Hex-encoded data. It is possible to
41 convert back and forth between Buffers and ordinary JavaScript string objects
42 by using an explicit encoding method.
45 const buf = new Buffer('hello world', 'ascii');
46 console.log(buf.toString('hex'));
47 // prints: 68656c6c6f20776f726c64
48 console.log(buf.toString('base64'));
49 // prints: aGVsbG8gd29ybGQ=
52 The character encodings currently supported by Node.js include:
54 * `'ascii'` - for 7-bit ASCII data only. This encoding method is very fast and
55 will strip the high bit if set.
57 * `'utf8'` - Multibyte encoded Unicode characters. Many web pages and other
58 document formats use UTF-8.
60 * `'utf16le'` - 2 or 4 bytes, little-endian encoded Unicode characters.
61 Surrogate pairs (U+10000 to U+10FFFF) are supported.
63 * `'ucs2'` - Alias of `'utf16le'`.
65 * `'base64'` - Base64 string encoding.
67 * `'binary'` - A way of encoding the buffer into a one-byte (`latin-1`)
68 encoded string. The string `'latin-1'` is not supported. Instead, pass
69 `'binary'` to use `'latin-1'` encoding.
71 * `'hex'` - Encode each byte as two hexadecimal characters.
73 ## Buffers and TypedArray
75 Buffers are also `Uint8Array` TypedArray instances. However, there are subtle
76 incompatibilities with the TypedArray specification in ECMAScript 2015. For
77 instance, while `ArrayBuffer#slice()` creates a copy of the slice,
78 the implementation of [`Buffer#slice()`][`buf.slice()`] creates a view over the
79 existing Buffer without copying, making `Buffer#slice()` far more efficient.
81 It is also possible to create new TypedArray instances from a `Buffer` with the
84 1. The Buffer instances's memory is copied to the TypedArray, not shared.
86 2. The Buffer's memory is interpreted as an array of distinct elements, and not
87 as a byte array of the target type. That is,
88 `new Uint32Array(new Buffer([1,2,3,4]))` creates a 4-element `Uint32Array`
89 with elements `[1,2,3,4]`, not a `Uint32Array` with a single element
90 `[0x1020304]` or `[0x4030201]`.
92 It is possible to create a new Buffer that shares the same allocated memory as
93 a TypedArray instance by using the TypeArray objects `.buffer` property:
96 const arr = new Uint16Array(2);
100 const buf1 = new Buffer(arr); // copies the buffer
101 const buf2 = new Buffer(arr.buffer); // shares the memory with arr;
104 // Prints: <Buffer 88 a0>, copied buffer has only two elements
106 // Prints: <Buffer 88 13 a0 0f>
110 // Prints: <Buffer 88 a0>
112 // Prints: <Buffer 88 13 70 17>
115 Note that when creating a Buffer using the TypeArray's `.buffer`, it is not
116 currently possible to use only a portion of the underlying `ArrayBuffer`. To
117 create a Buffer that uses only a part of the `ArrayBuffer`, use the
118 [`buf.slice()`][] function after the Buffer is created:
121 const arr = new Uint16Array(20);
122 const buf = new Buffer(arr.buffer).slice(0, 16);
123 console.log(buf.length);
127 ## Buffers and ES6 iteration
129 Buffers can be iterated over using the ECMAScript 2015 (ES6) `for..of` syntax:
132 const buf = new Buffer([1, 2, 3]);
143 Additionally, the [`buf.values()`][], [`buf.keys()`][], and
144 [`buf.entries()`][] methods can be used to create iterators.
148 The Buffer class is a global type for dealing with binary data directly.
149 It can be constructed in a variety of ways.
151 ### new Buffer(array)
155 Allocates a new Buffer using an `array` of octets.
158 const buf = new Buffer([0x62,0x75,0x66,0x66,0x65,0x72]);
159 // creates a new Buffer containing ASCII bytes
160 // ['b','u','f','f','e','r']
163 ### new Buffer(buffer)
167 Copies the passed `buffer` data onto a new `Buffer` instance.
170 const buf1 = new Buffer('buffer');
171 const buf2 = new Buffer(buf1);
174 console.log(buf1.toString());
176 console.log(buf2.toString());
177 // 'buffer' (copy is not changed)
180 ### new Buffer(arrayBuffer)
182 * `arrayBuffer` - The `.buffer` property of a `TypedArray` or a `new
185 When passed a reference to the `.buffer` property of a `TypedArray` instance,
186 the newly created Buffer will share the same allocated memory as the
190 const arr = new Uint16Array(2);
194 const buf = new Buffer(arr.buffer); // shares the memory with arr;
197 // Prints: <Buffer 88 13 a0 0f>
199 // changing the TypdArray changes the Buffer also
203 // Prints: <Buffer 88 13 70 17>
210 Allocates a new Buffer of `size` bytes. The `size` must be less than
211 or equal to the value of `require('buffer').kMaxLength` (on 64-bit
212 architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
213 thrown. If a `size` less than 0 is specified, a zero-length Buffer will be
216 Unlike `ArrayBuffers`, the underlying memory for Buffer instances created in
217 this way is not initialized. The contents of a newly created `Buffer` are
218 unknown and could contain sensitive data. Use [`buf.fill(0)`][] to initialize a
222 const buf = new Buffer(5);
224 // <Buffer 78 e0 82 02 01>
225 // (octets will be different, every time)
228 // <Buffer 00 00 00 00 00>
231 ### new Buffer(str[, encoding])
233 * `str` {String} String to encode.
234 * `encoding` {String} Default: `'utf8'`
236 Creates a new Buffer containing the given JavaScript string `str`. If
237 provided, the `encoding` parameter identifies the strings character encoding.
240 const buf1 = new Buffer('this is a tést');
241 console.log(buf1.toString());
242 // prints: this is a tést
243 console.log(buf1.toString('ascii'));
244 // prints: this is a tC)st
246 const buf2 = new Buffer('7468697320697320612074c3a97374', 'hex');
247 console.log(buf2.toString());
248 // prints: this is a tést
251 ### Class Method: Buffer.byteLength(string[, encoding])
254 * `encoding` {String} Default: `'utf8'`
257 Returns the actual byte length of a string. This is not the same as
258 [`String.prototype.length`][] since that returns the number of *characters* in
264 const str = '\u00bd + \u00bc = \u00be';
266 console.log(`${str}: ${str.length} characters, ` +
267 `${Buffer.byteLength(str, 'utf8')} bytes`);
269 // ½ + ¼ = ¾: 9 characters, 12 bytes
272 ### Class Method: Buffer.compare(buf1, buf2)
278 Compares `buf1` to `buf2` typically for the purpose of sorting arrays of
279 Buffers. This is equivalent is calling [`buf1.compare(buf2)`][].
282 const arr = [Buffer('1234'), Buffer('0123')];
283 arr.sort(Buffer.compare);
286 ### Class Method: Buffer.concat(list[, totalLength])
288 * `list` {Array} List of Buffer objects to concat
289 * `totalLength` {Number} Total length of the Buffers in the list when concatenated
292 Returns a new Buffer which is the result of concatenating all the Buffers in
295 If the list has no items, or if the `totalLength` is 0, then a new zero-length
298 If `totalLength` is not provided, it is calculated from the Buffers in the
299 `list`. This, however, adds an additional loop to the function, so it is faster
300 to provide the length explicitly.
302 Example: build a single Buffer from a list of three Buffers:
305 const buf1 = new Buffer(10).fill(0);
306 const buf2 = new Buffer(14).fill(0);
307 const buf3 = new Buffer(18).fill(0);
308 const totalLength = buf1.length + buf2.length + buf3.length;
310 console.log(totalLength);
311 const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
313 console.log(bufA.length);
316 // <Buffer 00 00 00 00 ...>
320 ### Class Method: Buffer.isBuffer(obj)
325 Returns 'true' if `obj` is a Buffer.
327 ### Class Method: Buffer.isEncoding(encoding)
329 * `encoding` {String} The encoding string to test
332 Returns true if the `encoding` is a valid encoding argument, or false
340 The index operator `[index]` can be used to get and set the octet at position
341 `index` in the Buffer. The values refer to individual bytes, so the legal value
342 range is between `0x00` and `0xFF` (hex) or `0` and `255` (decimal).
344 Example: copy an ASCII string into a Buffer, one byte at a time:
347 const str = "Node.js";
348 const buf = new Buffer(str.length);
350 for (var i = 0; i < str.length ; i++) {
351 buf[i] = str.charCodeAt(i);
358 ### buf.compare(otherBuffer)
360 * `otherBuffer` {Buffer}
363 Compares two Buffer instances and returns a number indicating whether `buf`
364 comes before, after, or is the same as the `otherBuffer` in sort order.
365 Comparison is based on the actual sequence of bytes in each Buffer.
367 * `0` is returned if `otherBuffer` is the same as `buf`
368 * `1` is returned if `otherBuffer` should come *before* `buf` when sorted.
369 * `-1` is returned if `otherBuffer` should come *after* `buf` when sorted.
372 const buf1 = new Buffer('ABC');
373 const buf2 = new Buffer('BCD');
374 const buf3 = new Buffer('ABCD');
376 console.log(buf1.compare(buf1));
378 console.log(buf1.compare(buf2));
380 console.log(buf1.compare(buf3));
382 console.log(buf2.compare(buf1));
384 console.log(buf2.compare(buf3));
387 [buf1, buf2, buf3].sort(Buffer.compare);
388 // produces sort order [buf1, buf3, buf2]
391 ### buf.copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]])
393 * `targetBuffer` {Buffer} Buffer to copy into
394 * `targetStart` {Number} Default: 0
395 * `sourceStart` {Number} Default: 0
396 * `sourceEnd` {Number} Default: `buffer.length`
397 * Return: {Number} The number of bytes copied.
399 Copies data from a region of this Buffer to a region in the target Buffer even
400 if the target memory region overlaps with the source.
402 Example: build two Buffers, then copy `buf1` from byte 16 through byte 19
403 into `buf2`, starting at the 8th byte in `buf2`.
406 const buf1 = new Buffer(26);
407 const buf2 = new Buffer(26).fill('!');
409 for (var i = 0 ; i < 26 ; i++) {
410 buf1[i] = i + 97; // 97 is ASCII a
413 buf1.copy(buf2, 8, 16, 20);
414 console.log(buf2.toString('ascii', 0, 25));
415 // Prints: !!!!!!!!qrst!!!!!!!!!!!!!
418 Example: Build a single Buffer, then copy data from one region to an overlapping
419 region in the same Buffer
422 const buf = new Buffer(26);
424 for (var i = 0 ; i < 26 ; i++) {
425 buf[i] = i + 97; // 97 is ASCII a
428 buf.copy(buf, 0, 4, 10);
429 console.log(buf.toString());
431 // efghijghijklmnopqrstuvwxyz
438 Creates and returns an [iterator][] of `[index, byte]` pairs from the Buffer
442 const buf = new Buffer('buffer');
443 for (var pair of buf.entries()) {
455 ### buf.equals(otherBuffer)
457 * `otherBuffer` {Buffer}
460 Returns a boolean indicating whether `this` and `otherBuffer` have exactly the
464 const buf1 = new Buffer('ABC');
465 const buf2 = new Buffer('414243', 'hex');
466 const buf3 = new Buffer('ABCD');
468 console.log(buf1.equals(buf2));
470 console.log(buf1.equals(buf3));
474 ### buf.fill(value[, offset[, end]])
476 * `value` {String|Number}
477 * `offset` {Number} Default: 0
478 * `end` {Number} Default: `buffer.length`
481 Fills the Buffer with the specified value. If the `offset` and `end` are not
482 given it will fill the entire Buffer. The method returns a reference to the
483 Buffer so calls can be chained.
486 const b = new Buffer(50).fill('h');
487 console.log(b.toString());
488 // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
491 ### buf.indexOf(value[, byteOffset][, encoding])
493 * `value` {String|Buffer|Number}
494 * `byteOffset` {Number} Default: 0
495 * `encoding` {String} Default: `'utf8'`
498 Operates similar to [`Array#indexOf()`][] in that it returns either the
499 starting index position of `value` in Buffer or `-1` if the Buffer does not
500 contain `value`. The `value` can be a String, Buffer or Number. Strings are by
501 default interpreted as UTF8. Buffers will use the entire Buffer (to compare a
502 partial Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255.
505 const buf = new Buffer('this is a buffer');
511 buf.indexOf(new Buffer('a buffer'));
513 buf.indexOf(97); // ascii for 'a'
515 buf.indexOf(new Buffer('a buffer example'));
517 buf.indexOf(new Buffer('a buffer example').slice(0,8));
520 const utf16Buffer = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
522 utf16Buffer.indexOf('\u03a3', 0, 'ucs2');
524 utf16Buffer.indexOf('\u03a3', -4, 'ucs2');
528 ### buf.includes(value[, byteOffset][, encoding])
530 * `value` {String|Buffer|Number}
531 * `byteOffset` {Number} Default: 0
532 * `encoding` {String} Default: `'utf8'`
535 Operates similar to [`Array#includes()`][]. The `value` can be a String, Buffer
536 or Number. Strings are interpreted as UTF8 unless overridden with the
537 `encoding` argument. Buffers will use the entire Buffer (to compare a partial
538 Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255.
540 The `byteOffset` indicates the index in `buf` where searching begins.
543 const buf = new Buffer('this is a buffer');
545 buf.includes('this');
549 buf.includes(new Buffer('a buffer'));
551 buf.includes(97); // ascii for 'a'
553 buf.includes(new Buffer('a buffer example'));
555 buf.includes(new Buffer('a buffer example').slice(0,8));
557 buf.includes('this', 4);
565 Creates and returns an [iterator][] of Buffer keys (indices).
568 const buf = new Buffer('buffer');
569 for (var key of buf.keys()) {
585 Returns the amount of memory allocated for the Buffer in number of bytes. Note
586 that this does not necessarily reflect the amount of usable data within the
587 Buffer. For instance, in the example below, a Buffer with 1234 bytes is
588 allocated, but only 11 ASCII bytes are written.
591 const buf = new Buffer(1234);
593 console.log(buf.length);
596 buf.write('some string', 0, 'ascii');
597 console.log(buf.length);
601 While the `length` property is not immutable, changing the value of `length`
602 can result in undefined and inconsistent behavior. Applications that wish to
603 modify the length of a Buffer should therefore treat `length` as read-only and
604 use [`buf.slice()`][] to create a new Buffer.
607 const buf = new Buffer(10);
608 buf.write('abcdefghj', 0, 'ascii');
609 console.log(buf.length);
611 buf = buf.slice(0,5);
612 console.log(buf.length);
616 ### buf.readDoubleBE(offset[, noAssert])
617 ### buf.readDoubleLE(offset[, noAssert])
619 * `offset` {Number} `0 <= offset <= buf.length - 8`
620 * `noAssert` {Boolean} Default: false
623 Reads a 64-bit double from the Buffer at the specified `offset` with specified
624 endian format (`readDoubleBE()` returns big endian, `readDoubleLE()` returns
627 Setting `noAssert` to `true` skips validation of the `offset`. This allows the
628 `offset` to be beyond the end of the Buffer.
631 const buf = new Buffer([1,2,3,4,5,6,7,8]);
634 // Returns: 8.20788039913184e-304
636 // Returns: 5.447603722011605e-270
638 // throws RangeError: Index out of range
640 buf.readDoubleLE(1, true); // Warning: reads passed end of buffer!
641 // Segmentation fault! don't do this!
644 ### buf.readFloatBE(offset[, noAssert])
645 ### buf.readFloatLE(offset[, noAssert])
647 * `offset` {Number} `0 <= offset <= buf.length - 4`
648 * `noAssert` {Boolean} Default: false
651 Reads a 32-bit float from the Buffer at the specified `offset` with specified
652 endian format (`readFloatBE()` returns big endian, `readFloatLE()` returns
655 Setting `noAssert` to `true` skips validation of the `offset`. This allows the
656 `offset` to be beyond the end of the Buffer.
659 const buf = new Buffer([1,2,3,4]);
662 // Returns: 2.387939260590663e-38
664 // Returns: 1.539989614439558e-36
666 // throws RangeError: Index out of range
668 buf.readFloatLE(1, true); // Warning: reads passed end of buffer!
669 // Segmentation fault! don't do this!
672 ### buf.readInt8(offset[, noAssert])
674 * `offset` {Number} `0 <= offset <= buf.length - 1`
675 * `noAssert` {Boolean} Default: false
678 Reads a signed 8-bit integer from the Buffer at the specified `offset`.
680 Setting `noAssert` to `true` skips validation of the `offset`. This allows the
681 `offset` to be beyond the end of the Buffer.
683 Integers read from the Buffer are interpreted as two's complement signed values.
686 const buf = new Buffer([1,-2,3,4]);
694 ### buf.readInt16BE(offset[, noAssert])
695 ### buf.readInt16LE(offset[, noAssert])
697 * `offset` {Number} `0 <= offset <= buf.length - 2`
698 * `noAssert` {Boolean} Default: false
701 Reads a signed 16-bit integer from the Buffer at the specified `offset` with
702 the specified endian format (`readInt16BE()` returns big endian,
703 `readInt16LE()` returns little endian).
705 Setting `noAssert` to `true` skips validation of the `offset`. This allows the
706 `offset` to be beyond the end of the Buffer.
708 Integers read from the Buffer are interpreted as two's complement signed values.
711 const buf = new Buffer([1,-2,3,4]);
719 ### buf.readInt32BE(offset[, noAssert])
720 ### buf.readInt32LE(offset[, noAssert])
722 * `offset` {Number} `0 <= offset <= buf.length - 4`
723 * `noAssert` {Boolean} Default: false
726 Reads a signed 32-bit integer from the Buffer at the specified `offset` with
727 the specified endian format (`readInt32BE()` returns big endian,
728 `readInt32LE()` returns little endian).
730 Setting `noAssert` to `true` skips validation of the `offset`. This allows the
731 `offset` to be beyond the end of the Buffer.
733 Integers read from the Buffer are interpreted as two's complement signed values.
736 const buf = new Buffer([1,-2,3,4]);
744 ### buf.readIntBE(offset, byteLength[, noAssert])
745 ### buf.readIntLE(offset, byteLength[, noAssert])
747 * `offset` {Number} `0 <= offset <= buf.length - byteLength`
748 * `byteLength` {Number} `0 < byteLength <= 6`
749 * `noAssert` {Boolean} Default: false
752 Reads `byteLength` number of bytes from the Buffer at the specified `offset`
753 and interprets the result as a two's complement signed value. Supports up to 48
754 bits of accuracy. For example:
757 const buf = new Buffer(6);
758 buf.writeUInt16LE(0x90ab, 0);
759 buf.writeUInt32LE(0x12345678, 2);
760 buf.readIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits)
761 // Returns: '1234567890ab'
763 buf.readIntBE(0, 6).toString(16);
764 // Returns: -546f87a9cbee
767 Setting `noAssert` to `true` skips validation of the `offset`. This allows the
768 `offset` to be beyond the end of the Buffer.
770 ### buf.readUInt8(offset[, noAssert])
772 * `offset` {Number} `0 <= offset <= buf.length - 1`
773 * `noAssert` {Boolean} Default: false
776 Reads an unsigned 8-bit integer from the Buffer at the specified `offset`.
778 Setting `noAssert` to `true` skips validation of the `offset`. This allows the
779 `offset` to be beyond the end of the Buffer.
782 const buf = new Buffer([1,-2,3,4]);
790 ### buf.readUInt16BE(offset[, noAssert])
791 ### buf.readUInt16LE(offset[, noAssert])
793 * `offset` {Number} `0 <= offset <= buf.length - 2`
794 * `noAssert` {Boolean} Default: false
797 Reads an unsigned 16-bit integer from the Buffer at the specified `offset` with
798 specified endian format (`readInt32BE()` returns big endian,
799 `readInt32LE()` returns little endian).
801 Setting `noAssert` to `true` skips validation of the `offset`. This allows the
802 `offset` to be beyond the end of the Buffer.
807 const buf = new Buffer([0x3, 0x4, 0x23, 0x42]);
823 ### buf.readUInt32BE(offset[, noAssert])
824 ### buf.readUInt32LE(offset[, noAssert])
826 * `offset` {Number} `0 <= offset <= buf.length - 4`
827 * `noAssert` {Boolean} Default: false
830 Reads an unsigned 32-bit integer from the Buffer at the specified `offset` with
831 specified endian format (`readInt32BE()` returns big endian,
832 `readInt32LE()` returns little endian).
834 Setting `noAssert` to `true` skips validation of the `offset`. This allows the
835 `offset` to be beyond the end of the Buffer.
840 const buf = new Buffer([0x3, 0x4, 0x23, 0x42]);
843 // Returns: 0x03042342
844 console.log(buf.readUInt32LE(0));
845 // Returns: 0x42230403
848 ### buf.readUIntBE(offset, byteLength[, noAssert])
849 ### buf.readUIntLE(offset, byteLength[, noAssert])
851 * `offset` {Number} `0 <= offset <= buf.length - byteLength`
852 * `byteLength` {Number} `0 < byteLength <= 6`
853 * `noAssert` {Boolean} Default: false
856 Reads `byteLength` number of bytes from the Buffer at the specified `offset`
857 and interprets the result as an unsigned integer. Supports up to 48
858 bits of accuracy. For example:
861 const buf = new Buffer(6);
862 buf.writeUInt16LE(0x90ab, 0);
863 buf.writeUInt32LE(0x12345678, 2);
864 buf.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits)
865 // Returns: '1234567890ab'
867 buf.readUIntBE(0, 6).toString(16);
868 // Returns: ab9078563412
871 Setting `noAssert` to `true` skips validation of the `offset`. This allows the
872 `offset` to be beyond the end of the Buffer.
874 ### buf.slice([start[, end]])
876 * `start` {Number} Default: 0
877 * `end` {Number} Default: `buffer.length`
880 Returns a new Buffer that references the same memory as the original, but
881 offset and cropped by the `start` and `end` indices.
883 **Note that modifying the new Buffer slice will modify the memory in the
884 original Buffer because the allocated memory of the two objects overlap.**
886 Example: build a Buffer with the ASCII alphabet, take a slice, then modify one
887 byte from the original Buffer.
890 const buf1 = new Buffer(26);
892 for (var i = 0 ; i < 26 ; i++) {
893 buf1[i] = i + 97; // 97 is ASCII a
896 const buf2 = buf1.slice(0, 3);
897 buf2.toString('ascii', 0, buf2.length);
900 buf2.toString('ascii', 0, buf2.length);
904 Specifying negative indexes causes the slice to be generated relative to the
905 end of the Buffer rather than the beginning.
908 const buf = new Buffer('buffer');
910 buf.slice(-6, -1).toString();
911 // Returns 'buffe', equivalent to buf.slice(0, 5)
912 buf.slice(-6, -2).toString();
913 // Returns 'buff', equivalent to buf.slice(0, 4)
914 buf.slice(-5, -2).toString();
915 // Returns 'uff', equivalent to buf.slice(1, 4)
918 ### buf.toString([encoding[, start[, end]]])
920 * `encoding` {String} Default: `'utf8'`
921 * `start` {Number} Default: 0
922 * `end` {Number} Default: `buffer.length`
925 Decodes and returns a string from the Buffer data using the specified
926 character set `encoding`.
929 const buf = new Buffer(26);
930 for (var i = 0 ; i < 26 ; i++) {
931 buf[i] = i + 97; // 97 is ASCII a
933 buf.toString('ascii');
934 // Returns: 'abcdefghijklmnopqrstuvwxyz'
935 buf.toString('ascii',0,5);
937 buf.toString('utf8',0,5);
939 buf.toString(undefined,0,5);
940 // Returns: 'abcde', encoding defaults to 'utf8'
947 Returns a JSON representation of the Buffer instance. [`JSON.stringify()`][]
948 implicitly calls this function when stringifying a Buffer instance.
953 const buf = new Buffer('test');
954 const json = JSON.stringify(buf);
957 // Prints: '{"type":"Buffer","data":[116,101,115,116]}'
959 const copy = JSON.parse(json, (key, value) => {
960 return value && value.type === 'Buffer'
961 ? new Buffer(value.data)
965 console.log(copy.toString());
973 Creates and returns an [iterator][] for Buffer values (bytes). This function is
974 called automatically when the Buffer is used in a `for..of` statement.
977 const buf = new Buffer('buffer');
978 for (var value of buf.values()) {
989 for (var value of buf) {
1001 ### buf.write(string[, offset[, length]][, encoding])
1003 * `string` {String} Bytes to be written to buffer
1004 * `offset` {Number} Default: 0
1005 * `length` {Number} Default: `buffer.length - offset`
1006 * `encoding` {String} Default: `'utf8'`
1007 * Return: {Number} Numbers of bytes written
1009 Writes `string` to the Buffer at `offset` using the given `encoding`.
1010 The `length` parameter is the number of bytes to write. If the Buffer did not
1011 contain enough space to fit the entire string, only a partial amount of the
1012 string will be written however, it will not write only partially encoded
1016 const buf = new Buffer(256);
1017 const len = buf.write('\u00bd + \u00bc = \u00be', 0);
1018 console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
1019 // Prints: 12 bytes: ½ + ¼ = ¾
1022 ### buf.writeDoubleBE(value, offset[, noAssert])
1023 ### buf.writeDoubleLE(value, offset[, noAssert])
1025 * `value` {Number} Bytes to be written to Buffer
1026 * `offset` {Number} `0 <= offset <= buf.length - 8`
1027 * `noAssert` {Boolean} Default: false
1028 * Return: {Number} Numbers of bytes written
1030 Writes `value` to the Buffer at the specified `offset` with specified endian
1031 format (`writeDoubleBE()` writes big endian, `writeDoubleLE()` writes little
1032 endian). The `value` argument must be a valid 64-bit double.
1034 Set `noAssert` to true to skip validation of `value` and `offset`. This means
1035 that `value` may be too large for the specific function and `offset` may be
1036 beyond the end of the Buffer leading to the values being silently dropped. This
1037 should not be used unless you are certain of correctness.
1042 const buf = new Buffer(8);
1043 buf.writeDoubleBE(0xdeadbeefcafebabe, 0);
1046 // Prints: <Buffer 43 eb d5 b7 dd f9 5f d7>
1048 buf.writeDoubleLE(0xdeadbeefcafebabe, 0);
1051 // Prints: <Buffer d7 5f f9 dd b7 d5 eb 43>
1054 ### buf.writeFloatBE(value, offset[, noAssert])
1055 ### buf.writeFloatLE(value, offset[, noAssert])
1057 * `value` {Number} Bytes to be written to Buffer
1058 * `offset` {Number} `0 <= offset <= buf.length - 4`
1059 * `noAssert` {Boolean} Default: false
1060 * Return: {Number} Numbers of bytes written
1062 Writes `value` to the Buffer at the specified `offset` with specified endian
1063 format (`writeFloatBE()` writes big endian, `writeFloatLE()` writes little
1064 endian). Behavior is unspecified if `value` is anything other than a 32-bit
1067 Set `noAssert` to true to skip validation of `value` and `offset`. This means
1068 that `value` may be too large for the specific function and `offset` may be
1069 beyond the end of the Buffer leading to the values being silently dropped. This
1070 should not be used unless you are certain of correctness.
1075 const buf = new Buffer(4);
1076 buf.writeFloatBE(0xcafebabe, 0);
1079 // Prints: <Buffer 4f 4a fe bb>
1081 buf.writeFloatLE(0xcafebabe, 0);
1084 // Prints: <Buffer bb fe 4a 4f>
1087 ### buf.writeInt8(value, offset[, noAssert])
1089 * `value` {Number} Bytes to be written to Buffer
1090 * `offset` {Number} `0 <= offset <= buf.length - 1`
1091 * `noAssert` {Boolean} Default: false
1092 * Return: {Number} Numbers of bytes written
1094 Writes `value` to the Buffer at the specified `offset`. The `value` must be a
1095 valid signed 8-bit integer.
1097 Set `noAssert` to true to skip validation of `value` and `offset`. This means
1098 that `value` may be too large for the specific function and `offset` may be
1099 beyond the end of the Buffer leading to the values being silently dropped. This
1100 should not be used unless you are certain of correctness.
1102 The `value` is interpreted and written as a two's complement signed integer.
1105 const buf = new Buffer(2);
1106 buf.writeInt8(2, 0);
1107 buf.writeInt8(-2, 1);
1109 // Prints: <Buffer 02 fe>
1112 ### buf.writeInt16BE(value, offset[, noAssert])
1113 ### buf.writeInt16LE(value, offset[, noAssert])
1115 * `value` {Number} Bytes to be written to Buffer
1116 * `offset` {Number} `0 <= offset <= buf.length - 2`
1117 * `noAssert` {Boolean} Default: false
1118 * Return: {Number} Numbers of bytes written
1120 Writes `value` to the Buffer at the specified `offset` with specified endian
1121 format (`writeInt16BE()` writes big endian, `writeInt16LE()` writes little
1122 endian). The `value` must be a valid signed 16-bit integer.
1124 Set `noAssert` to true to skip validation of `value` and `offset`. This means
1125 that `value` may be too large for the specific function and `offset` may be
1126 beyond the end of the Buffer leading to the values being silently dropped. This
1127 should not be used unless you are certain of correctness.
1129 The `value` is interpreted and written as a two's complement signed integer.
1132 const buf = new Buffer(4);
1133 buf.writeInt16BE(0x0102,0);
1134 buf.writeInt16LE(0x0304,2);
1136 // Prints: <Buffer 01 02 04 03>
1139 ### buf.writeInt32BE(value, offset[, noAssert])
1140 ### buf.writeInt32LE(value, offset[, noAssert])
1142 * `value` {Number} Bytes to be written to Buffer
1143 * `offset` {Number} `0 <= offset <= buf.length - 4`
1144 * `noAssert` {Boolean} Default: false
1145 * Return: {Number} Numbers of bytes written
1147 Writes `value` to the Buffer at the specified `offset` with specified endian
1148 format (`writeInt32BE()` writes big endian, `writeInt32LE()` writes little
1149 endian). The `value` must be a valid signed 32-bit integer.
1151 Set `noAssert` to true to skip validation of `value` and `offset`. This means
1152 that `value` may be too large for the specific function and `offset` may be
1153 beyond the end of the Buffer leading to the values being silently dropped. This
1154 should not be used unless you are certain of correctness.
1156 The `value` is interpreted and written as a two's complement signed integer.
1159 const buf = new Buffer(8);
1160 buf.writeInt32BE(0x01020304,0);
1161 buf.writeInt32LE(0x05060708,4);
1163 // Prints: <Buffer 01 02 03 04 08 07 06 05>
1166 ### buf.writeIntBE(value, offset, byteLength[, noAssert])
1167 ### buf.writeIntLE(value, offset, byteLength[, noAssert])
1169 * `value` {Number} Bytes to be written to Buffer
1170 * `offset` {Number} `0 <= offset <= buf.length - byteLength`
1171 * `byteLength` {Number} `0 < byteLength <= 6`
1172 * `noAssert` {Boolean} Default: false
1173 * Return: {Number} Numbers of bytes written
1175 Writes `value` to the Buffer at the specified `offset` and `byteLength`.
1176 Supports up to 48 bits of accuracy. For example:
1179 const buf1 = new Buffer(6);
1180 buf1.writeUIntBE(0x1234567890ab, 0, 6);
1182 // Prints: <Buffer 12 34 56 78 90 ab>
1184 const buf2 = new Buffer(6);
1185 buf2.writeUIntLE(0x1234567890ab, 0, 6);
1187 // Prints: <Buffer ab 90 78 56 34 12>
1190 Set `noAssert` to true to skip validation of `value` and `offset`. This means
1191 that `value` may be too large for the specific function and `offset` may be
1192 beyond the end of the Buffer leading to the values being silently dropped. This
1193 should not be used unless you are certain of correctness.
1195 ### buf.writeUInt8(value, offset[, noAssert])
1197 * `value` {Number} Bytes to be written to Buffer
1198 * `offset` {Number} `0 <= offset <= buf.length - 1`
1199 * `noAssert` {Boolean} Default: false
1200 * Return: {Number} Numbers of bytes written
1202 Writes `value` to the Buffer at the specified `offset`. The `value` must be a
1203 valid unsigned 8-bit integer.
1205 Set `noAssert` to true to skip validation of `value` and `offset`. This means
1206 that `value` may be too large for the specific function and `offset` may be
1207 beyond the end of the Buffer leading to the values being silently dropped. This
1208 should not be used unless you are certain of correctness.
1213 const buf = new Buffer(4);
1214 buf.writeUInt8(0x3, 0);
1215 buf.writeUInt8(0x4, 1);
1216 buf.writeUInt8(0x23, 2);
1217 buf.writeUInt8(0x42, 3);
1220 // Prints: <Buffer 03 04 23 42>
1223 ### buf.writeUInt16BE(value, offset[, noAssert])
1224 ### buf.writeUInt16LE(value, offset[, noAssert])
1226 * `value` {Number} Bytes to be written to Buffer
1227 * `offset` {Number} `0 <= offset <= buf.length - 2`
1228 * `noAssert` {Boolean} Default: false
1229 * Return: {Number} Numbers of bytes written
1231 Writes `value` to the Buffer at the specified `offset` with specified endian
1232 format (`writeUInt16BE()` writes big endian, `writeUInt16LE()` writes little
1233 endian). The `value` must be a valid unsigned 16-bit integer.
1235 Set `noAssert` to true to skip validation of `value` and `offset`. This means
1236 that `value` may be too large for the specific function and `offset` may be
1237 beyond the end of the Buffer leading to the values being silently dropped. This
1238 should not be used unless you are certain of correctness.
1243 const buf = new Buffer(4);
1244 buf.writeUInt16BE(0xdead, 0);
1245 buf.writeUInt16BE(0xbeef, 2);
1248 // Prints: <Buffer de ad be ef>
1250 buf.writeUInt16LE(0xdead, 0);
1251 buf.writeUInt16LE(0xbeef, 2);
1254 // Prints: <Buffer ad de ef be>
1257 ### buf.writeUInt32BE(value, offset[, noAssert])
1258 ### buf.writeUInt32LE(value, offset[, noAssert])
1260 * `value` {Number} Bytes to be written to Buffer
1261 * `offset` {Number} `0 <= offset <= buf.length - 4`
1262 * `noAssert` {Boolean} Default: false
1263 * Return: {Number} Numbers of bytes written
1265 Writes `value` to the Buffer at the specified `offset` with specified endian
1266 format (`writeUInt32BE()` writes big endian, `writeUInt32LE()` writes little
1267 endian). The `value` must be a valid unsigned 32-bit integer.
1269 Set `noAssert` to true to skip validation of `value` and `offset`. This means
1270 that `value` may be too large for the specific function and `offset` may be
1271 beyond the end of the Buffer leading to the values being silently dropped. This
1272 should not be used unless you are certain of correctness.
1277 const buf = new Buffer(4);
1278 buf.writeUInt32BE(0xfeedface, 0);
1281 // Prints: <Buffer fe ed fa ce>
1283 buf.writeUInt32LE(0xfeedface, 0);
1286 // Prints: <Buffer ce fa ed fe>
1289 ### buf.writeUIntBE(value, offset, byteLength[, noAssert])
1290 ### buf.writeUIntLE(value, offset, byteLength[, noAssert])
1292 * `value` {Number} Bytes to be written to Buffer
1293 * `offset` {Number} `0 <= offset <= buf.length - byteLength`
1294 * `byteLength` {Number} `0 < byteLength <= 6`
1295 * `noAssert` {Boolean} Default: false
1296 * Return: {Number} Numbers of bytes written
1298 Writes `value` to the Buffer at the specified `offset` and `byteLength`.
1299 Supports up to 48 bits of accuracy. For example:
1302 const buf = new Buffer(6);
1303 buf.writeUIntBE(0x1234567890ab, 0, 6);
1305 // Prints: <Buffer 12 34 56 78 90 ab>
1308 Set `noAssert` to true to skip validation of `value` and `offset`. This means
1309 that `value` may be too large for the specific function and `offset` may be
1310 beyond the end of the Buffer leading to the values being silently dropped. This
1311 should not be used unless you are certain of correctness.
1313 ## buffer.INSPECT_MAX_BYTES
1315 * {Number} Default: 50
1317 Returns the maximum number of bytes that will be returned when
1318 `buffer.inspect()` is called. This can be overridden by user modules. See
1319 [`util.inspect()`][] for more details on `buffer.inspect()` behavior.
1321 Note that this is a property on the `buffer` module as returned by
1322 `require('buffer')`, not on the Buffer global or a Buffer instance.
1324 ## Class: SlowBuffer
1326 Returns an un-pooled `Buffer`.
1328 In order to avoid the garbage collection overhead of creating many individually
1329 allocated Buffers, by default allocations under 4KB are sliced from a single
1330 larger allocated object. This approach improves both performance and memory
1331 usage since v8 does not need to track and cleanup as many `Persistent` objects.
1333 In the case where a developer may need to retain a small chunk of memory from a
1334 pool for an indeterminate amount of time, it may be appropriate to create an
1335 un-pooled Buffer instance using `SlowBuffer` then copy out the relevant bits.
1338 // need to keep around a few small chunks of memory
1341 socket.on('readable', () => {
1342 var data = socket.read();
1343 // allocate for retained data
1344 var sb = new SlowBuffer(10);
1345 // copy the data into the new allocation
1346 data.copy(sb, 0, 0, 10);
1351 Use of `SlowBuffer` should be used only as a last resort *after* a developer
1352 has observed undue memory retention in their applications.
1354 [`Array#includes()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
1355 [`Array#indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
1356 [`buf.entries()`]: #buffer_buf_entries
1357 [`buf.fill(0)`]: #buffer_buf_fill_value_offset_end
1358 [`buf.keys()`]: #buffer_buf_keys
1359 [`buf.slice()`]: #buffer_buf_slice_start_end
1360 [`buf.values()`]: #buffer_buf_values
1361 [`buf1.compare(buf2)`]: #buffer_buf_compare_otherbuffer
1362 [`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
1363 [`RangeError`]: errors.html#errors_class_rangeerror
1364 [`String.prototype.length`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
1365 [`util.inspect()`]: util.html#util_util_inspect_object_options
1366 [iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols