Node.js defines a Buffer class that creates a Buffer for binary data. The Buffer class is in global scope, so require(‘ Buffer ‘) is not required.

1. Create

Const buf1 = buffer.alloc (10); // Create a zero-filled Buffer of length 10 const buf1 = buffer.alloc (10); console.log(buf1); // Create a Buffer of length 10 filled with bytes of value '1' const buf2 = buffer.alloc (10, 1); console.log(buf2); / Create Buffer with bytes [1,2,3] const buf4 = buffer. from([1, 2,3]); console.log(buf4);Copy the code

2. The conversion

Const buf = buffer. from('hello world', 'utf8'); const buf = buffer. from('hello world', 'utf8'); The console. The log (` output buf ${buf} `); // buffer toString console.log(buf.tostring ()) // buffer to json const buf6 = buffer. from([0x1, 0x2, 0x3, 0x4, 0x5]); console.log(buf.toJSON())Copy the code

3. The merger

  • Buffer.concat([buf1,buf2], totalLength) totalLength is not required, if not provided it will be iterated over to calculate totalLength
const concat1 = Buffer.from('this is a ');
const concat2 = Buffer.from('book');
const concat3 = Buffer.concat([concat1, concat2], concat1.length + concat2.length);
console.log(concat3.toString());
Copy the code

4. To empty

// the quickest way to empty buffer data is buffer.fill(0) const tempBuf = buffer.alloc (10,1); console.log(tempBuf); console.log(tempBuf.fill(0));Copy the code