A Buffer is the built-in type of Node.js that represents an area of memory used to hold binary data. It can be thought of as a binary array.

Buffer can be used to represent binary data such as pictures and videos. In addition, the data we read from files and receive from the network are also Buffer data. Therefore, it is necessary to learn Buffer.

Buffers are in global scope, so there is no need to introduce buffers by requiring (‘ Buffer ‘).

First in personal blog, welcome to visit.

Creating a Buffer object

alloc

Buffer.alloc(size, [fill], [encoding]) can be used to allocate a size byte of memory, and two optional arguments can be received

  • Fill: Fill each byte in the Buffer with fill
  • Encoding: If fill is a string, the string is encoded as binary using encoding

When the fill parameter is not specified, the default is to fill 0.

const buf1 = Buffer.alloc(5);
console.log(buf1); // <Buffer 00 00 00 00 00>

const buf2 = Buffer.alloc(10.1);
console.log(buf2); // <Buffer 01 01 01 01 01 01 01 01 01 01>

const buf3 = Buffer.alloc(12."hello world!"."utf-8");
console.log(buf3); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 21>
Copy the code

AllocUnsafe (size) can also be used to allocate memory of a specified size, though 0 is not filled by default, and the contents are uncertain

const buf = Buffer.allocUnsafe(5);
console.log(buf); // <Buffer c0 84 7c 2a 7b>
Copy the code

We can specify values for the Buffer object fill using the fill(fill, encoding) method

const buf = Buffer.allocUnsafe(5);
buf.fill(0);
console.log(buf); // <Buffer 00 00 00 00 00>
Copy the code

from

We can also create a Buffer object using the buffer.from () method. The arguments that the FROM method accepts include arrays, strings, Buffer objects, objects, and so on.

Receive an integer array with integers between 0 and 255. Numbers beyond this range will be truncated

const buf = Buffer.from([1.2.3.4.5]);
console.log(buf); // <Buffer 01 02 03 04 05>
Copy the code

We can also pass in a string and specify an encoding, which encodes the string to binary using the specified encoding, or utF-8 by default if no encoding is specified

const buf = Buffer.from("hello"."utf-8");
console.log(buf); // <Buffer 68 65 6c 6c 6f>
Copy the code

The FROM method can also receive a Buffer object, which copies the data from the incoming Buffer object into the new Buffer object

const buf1 = Buffer.from("hello"."utf-8");
const buf2 = Buffer.from(buf1);

console.log(buf1 === buf2); // false
console.log(buf2.toString()); // hello
Copy the code

The FROM method can also receive an object, which, when passed in, is first converted to its original value and then converted to the corresponding binary array based on the original value

let obj = {
  [Symbol.toPrimitive](hint) {
    return "a"; }};const buf = Buffer.from(obj);
console.log(buf.toString()); // a
Copy the code

Properties of a Buffer object

length

The length property tells you the length of the Buffer array

const buf = Buffer.from("Hello World!");

console.log(buf.length); / / 12
Copy the code

buffer

The actual storage inside the Buffer object is an ArrayBuffer object, which can be obtained through the Buffer property

const buf = Buffer.alloc(5);

console.log(buf.buffer); // ArrayBuffer { [Uint8Contents]: <00 00 00 00 00>, byteLength: 5 }
Copy the code

Read Buffer object

This section describes how to access the contents of a Buffer object.

The subscript

As mentioned at the beginning of this article, we can think of a Buffer as a binary array, and since it is an array, the contents of the array can be accessed using subscripts.

const buf = Buffer.from([1.2.3.4.5]);
console.log(buf[0]); / / 1
console.log(buf[5]); // undefined
Copy the code

They parse the byte as a complement and return the corresponding number.

readXxx

We can also access the contents of a Buffer object using methods such as buf.readint8 () buf.readint16 () buf.readuint8 () buf.readuint16 ().

const buf = Buffer.from([1.2.3.4.5]);
console.log(buf.readInt8(2)); / / 3

// A RangeError is raised when accessing content that is out of scope
console.log(buf.readInt8(5)); // RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range.
Copy the code

The iterator

The iterator for a Buffer object is the same as the iterator for an array

  • entries
  • keys
  • values

We access the contents of the Buffer object by iterating through the iterator.

const buf = Buffer.from([3.4.2]);

for (let entry of buf.entries()) {
  // One element of the array is the subscript, and the second element is the corresponding element of the subscript
  console.log(entry); // [0, 3]
                      // [1, 4]
                      // [2, 2]
}
Copy the code
for (let key of buf.keys()) {
  console.log(key); / / 0
                    / / 1
                    / / 2
}
Copy the code
for (let value of buf.values()) {
  console.log(value); / / 3
                      / / 4
                      / / 2
}
Copy the code

Write a Buffer object

This section explains how to write to a Buffer object.

The subscript

We can change the contents of a Buffer object directly by subscripting it

const buf = Buffer.from([1.2.3]);

// Set the value by subscript
buf[0] = 4;

console.log(buf); // <Buffer 04 02 03>
Copy the code

write

We can write(string, [offset], [length], [encoding]) to Buffer:

  • String: Indicates the character string to be written
  • Offset: indicates the offset, that is, the offset is skipped to start writing. The default value is 0
  • Length: indicates the maximum number of bytes to be writtenbuf.length - offset, the default value isbuf.length - offset
  • Encoding: Specifies the encoding. The default value is encodingutf-8

This method returns the number of bytes that have been written.

const buf = Buffer.from([1.2.3.4]);

// Skip 1 byte to start writing, 1hi4
buf.write("hi".1);

console.log(buf); // <Buffer 01 68 69 04>
Copy the code

writeXxx

As with readXxx, we can write data to buF using the writeInt8() method, which takes two arguments:

  • Value: indicates the value to be written
  • Offset: indicates the offset. The default value is 0
const buf = Buffer.alloc(5);

buf.writeInt8(1.0);
buf.writeInt8(3.1);

console.log(buf); // <Buffer 01 03 00 00 00>
Copy the code

There is no writeInt16(), but there is writeInt16BE() and writeInt16LE(), which represent writing in big-enode and little-enode respectively.

Other methods

isBuffer

This method receives an object that is used to determine if the object is a Buffer object

let obj1 = {};
let obj2 = Buffer.alloc(3);

console.log(Buffer.isBuffer(obj1)); // false
console.log(Buffer.isBuffer(obj2)); // true
Copy the code

isEncoding

This method takes a string representing the encoding and returns whether the Buffer supports the encoding or true if it does, or false otherwise

console.log(Buffer.isEncoding("utf-8")); // true
console.log(Buffer.isEncoding("utf8"));  // true
console.log(Buffer.isEncoding("hex"));   // true
console.log(Buffer.isEncoding("latin")); // false
console.log(Buffer.isEncoding("gbk"));   // false
Copy the code

slice

Slice (start, end) returns a new Buffer object, with start and end representing the start and end positions of the Buffer. These parameters are optional. Start defaults to 0 and end defaults to buf.length. The returned Buffer objects reference the same block of memory as the original object, that is, their Buffer properties are the same.

const buffer = Buffer.from("hello world!");

const newBuffer = buffer.slice(6); // Trim the content after 6 to the new array
console.log(newBuffer.toString()); // world!

console.log(buffer.buffer === newBuffer.buffer); // true
Copy the code

subarray

Subarray (start, end) is almost equivalent to the slice method. The semantics of subarray are different, but the behavior is consistent. The semantics of subarray refer to returning a subarray of a range of the original array, while the semantics of slice refer to trimming. Similarly, subarray returns a new Buffer, and the returned Buffer has the same Buffer properties as the original Buffer.

const buffer = Buffer.from("hello world!");

const newBuffer = buffer.subarray(6);
console.log(newBuffer.toString()); // world!

console.log(buffer.buffer === newBuffer.buffer); // true
Copy the code

copy

copy(target, [targetStart], [sourceStart], [sourceEnd]) copies the contents of source from sourceStart to sourceEnd to target from targetStart, as shown in the GIF below

Except for target, the other three parameters are optional. The default value of targetStart and sourceStart is 0, and the default value of sourceEnd is buf.length.

const buf1 = Buffer.from("HelloWorld");
const buf2 = Buffer.alloc(8);

buf1.copy(buf2, 0.1.9);

console.log(buf2.toString()); // elloWorl
Copy the code

includes

The buf.includes(value, [offset], [encoding]) method checks whether the value is in the BUF.

A value can be a string, a Buffer object, or an integer. Offset is used to specify the search scope, indicating that the search starts from offset. The default value is 0. Enconding indicates the encoding. The default is UTF-8.

const buf = Buffer.from("HelloWorld");

// The search starts from 0 by default
console.log(buf.includes("H")); // true
// Start the search from 1 without H
console.log(buf.includes("H".1)); // false

console.log(buf.includes(Buffer.from("Hello"))); // true

// H corresponds to utF-8 encoding 72
console.log(buf.includes(72)); // true
Copy the code

indexOf

Buf.indexof (value, [offset], [encoding]) is used to find the subscript of value in buf. This parameter has the same meaning as includes. So includes(value) is equivalent to indexOf(value)! = = 1

const buf = Buffer.from("HelloWorld");

console.log(buf.indexOf("H")); / / 0
console.log(buf.indexOf("H".1)); // -1
console.log(buf.indexOf(Buffer.from("World"))); / / 5
console.log(buf.indexOf(72)); / / 0
Copy the code

equals

Buf. equals(otherBuffer) compares whether the bytes of two Buffer objects are identical, returning true if they are, and false otherwise

const buf1 = Buffer.alloc(5);
const buf2 = Buffer.alloc(5);
const buf3 = Buffer.allocUnsafe(5);

console.log(buf1.equals(buf2)); // true
console.log(buf1.equals(buf3)); // false
Copy the code

reference

  • Buffer | Node. Js document