Buffer: AN area of memory (outside the V8 heap memory) dedicated to temporary data, containing a specified number of bytes or characters. As opposed to strings, buffers are particularly useful for storing binary data.

An instance of the Buffer type is similar to an array of integers ranging from 0 to 255, where each element is a one-byte hexadecimal integer; Once created, it cannot be resized. Unlike a String, any part of a Buffer can be modified.

The Buffer class is a member of the global object, so use this module without requiring (‘ Buffer ‘).

Creating a Buffer instance

An instance of a Buffer object, which can be obtained by reading a file or constructed directly:

// Create a Buffer of length 10 filled with zero.
const buf1 = Buffer.alloc(10);

// Create a Buffer of length 10 filled with 0x1.
const buf2 = Buffer.alloc(10.1);

// Create an uninitialized Buffer of length 10.
// This method is faster than calling buffer.alloc (),
// However, the returned Buffer instance may contain old data,
// Therefore you need to rewrite it with fill() or write().
const buf3 = Buffer.allocUnsafe(10);

// Create a three-byte buffer of 0x01, 0x0A, 0xFF
const buf4=Buffer.from([1.10.255]);

// Create a 4-byte buffer of 0x61,0x62,0x41,0x42
const buf5=Buffer.from('abAB');

// Create a 6-byte buffer of 0xe4, 0xB8,0xe4,0xba, 0x8C
const buf6=Buffer.from('一二'.'utf8');
Copy the code

In versions of Node.js prior to 6.0.0, Buffer instances were created using the Buffer constructor. Various forms of the new Buffer() constructor have been deprecated in order to make Buffer instance creation more reliable and less error-prone. Instead, use separate buffer.from (), buffer.alloc (), and buffer.allocunsafe () methods.

The method name instructions
Buffer.alloc (size[,fill]) Returns a newly initialized Buffer of the specified size. Size must be a number, and the second argument can specify the Buffer data to fill.
Buffer.allocUnsafe(size )/Buffer.allocUnsafeSlow(size) Returns a new, uninitialized Buffer of the specified size. If size is less than or equal to half of buffer.poolsize, the Buffer instance returned by buffer.allocunsafe () may be allocated from a shared internal memory pool. Buffer.allocunsafeslow () returns instances that never use a shared internal memory pool.
Buffer.from(string[, encoding]) Returns a new Buffer containing a copy of the supplied string. You can specify the encoding format

Node.js currently supports the following character encodings:

ascii Applies only to 7-bit ASCII data. This encoding is fast and, if set, strips high bits.
utf8

Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8.
utf16le

A 2 – or 4-byte, little-endian encoded Unicode character. Proxy pairs (U+10000 to U+10FFFF) are supported.
ucs2

Alias of UTF16LE.
base64

Base64 encoding. This encoding also correctly accepts the “URL and filename safety letters” specified in section 5 of RFC 4648 when creating buffers from strings.
latin1

A method of encoding buffers as single-byte encoded strings (defined by IANA in RFC 1345, p. 63, as complementary blocks to Latin-1 and C0/C1 control codes).
binary Alias of latin1.
hex Encodes each byte into two hexadecimal characters.

Conversion between Buffer and String

buf.write(str,offset) STR string, offset corresponds to the offset in buffer

Convert String to Buffer:

var s1='AA';
var s2='BB';
var s3='CC';
var buf1=Buffer.alloc(6);
buf1.write(s1);
buf1.write(s2,2);
buf1.write(s3,4);
console.log(buf1);
console.log(buf1.toString());
//<Buffer 41 41 42 42 43 43>
//AABBCC
Copy the code

Convert the contents of a Buffer to a specially encoded String:

console.log(buf.toString());				// The default encoding is UTF-8
console.log(buf.toString('binary'));
console.log(buf.toString('hex'));
console.log(buf.toString('ascii'));
console.log(buf.toString('utf8'));
console.log(buf.toString('utf16le'));
console.log(buf.toString('base64'));
Copy the code

Traverse the Buffer

You can use a for loop with buf.length and buf[index] to iterate over each data in the buffer, or you can use the new ES6 feature for… The of loop iterates through each data value.

// Create a buffer of 8 bytes
const buf=Buffer.from('ab one');
// Use the for loop to iterate through the buffer
for(var i=0; i<buf.length; i++){console.log('%d-%s',buf[i],buf[i].toString(16))}/ / used for... Of traverses the buffer
for(var v of buf){
	console.log('%d-%s',v,v.toString(16))}Copy the code

Common Operations of Buffer

Member name instructions
buf.compare( ) Compare the sizes of two buffers
buf.copy( ) Copy the (partial) contents of a buffer
buf.equals( ) Determines whether the contents of two buffers are exactly the same
buf.fill( ) Populates the buffer with the specified value
buf.indexOf( ) Specifies the value at the beginning of the buffer
buf.includes( ) Checks whether the specified value is included
buf.slice( ) Returns the partial value of a buffer (no new buffer is returned, but a subset of the original buffer is returned. Modifying the return value changes the value of the original buffer.)
buf.toJSON( ) Convert to JOSN string format
buf.write( ) Writes the specified value to the specified position in the buffer

Copy the contents of two buffers into the same buffer:

const buf1=Buffer.from('ABC');
const buf2=Buffer.from('One, two, three');
var buf3=Buffer.alloc(buf1.length+buf2.length);// Create a buffer of the specified length
buf1.copy(buf3);// Copy buF1 buffer data to BUF3 with default offset starting at 0
buf2.copy(buf3,buf1.length);// Copy the buF2 buffer data to BUF3 with the offset at the end of buf1
console.log(buf3.toString());
/ / ABC in 123
Copy the code

Buf. slice does not return a new buffer. Instead, it returns a subset of the original buffer. Modifying the return value changes the value of the original buffer:

const buf1=Buffer.from('ABC');
console.log(buf1);

var sub=buf1.slice(2);
console.log(sub);

sub[0] =0x44;
console.log(sub);
console.log(buf1)
//<Buffer 41 42 43>
//<Buffer 43>
//<Buffer 44>
//<Buffer 41 42 44>
Copy the code