Home >Web Front-end >JS Tutorial >Detailed explanation of the operations of Buffer objects in Node.js (creation, reading and writing)

Detailed explanation of the operations of Buffer objects in Node.js (creation, reading and writing)

青灯夜游
青灯夜游forward
2021-12-23 18:55:513608browse

This article will take you to understand the Buffer object in Node, and introduce the methods of creating, reading and writing Buffer objects. I hope it will be helpful to you!

Detailed explanation of the operations of Buffer objects in Node.js (creation, reading and writing)

Buffer is a built-in type of Node.js. It is used to represent an area in memory to save binary data. It can be Think of it as a binary array.

Buffer can be used to represent binary data such as pictures and videos. In addition, the data we read from the file is also Buffer type data, and the data received from the network is also Buffer type data, so learning Buffer is still Very necessary.

Buffer is in the global scope, so there is no need to introduce Buffer through require('buffer').

Create Buffer object

alloc

We can passBuffer.alloc(size, [fill], [encoding]) To allocate a size byte size memory, you can also receive two optional parameters

  • fill: Use fill to fill every byte in the Buffer
  • encoding: If fill is a string, then use encoding to encode the string into binary

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>

We can also use allocUnsafe(size) to allocate memory of a specified size, but it will not be filled with 0 by default, and the content is uncertain

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

We can pass fill(fill, encoding) method fills the specified value for the Buffer object

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

from

We can also pass Buffer.from( ) method to create a Buffer object. The from method can receive parameters including arrays, strings, Buffer objects, objects and other types.

Receive an integer array. The integers in the array should be between 0~255. Numbers outside this range will be truncated.

const buf = Buffer.from([1, 2, 3, 4, 5]);
console.log(buf); // <Buffer 01 02 03 04 05>

We can also like Pass in a string and specify the encoding. It will encode the string into binary using the specified encoding. If no encoding is specified, the default encoding is utf-8

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

## The #from method can also receive a Buffer object, which will copy the data in the incoming Buffer object to 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

from The method can also receive an object , when an object is passed in, the object will first be converted into the original value, and then converted into 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

Buffer object properties

length

You can know the length of the Buffer array through the length property

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

console.log(buf.length); // 12

buffer

The actual data stored inside the Buffer object is an ArrayBuffer object, through the buffer property You can get this object

const buf = Buffer.alloc(5);

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

Read the Buffer object

This section introduces how to access the contents of the Buffer object.

Subscript

As mentioned at the beginning of the article, we can regard the Buffer object as a binary array. Since it is an array, we can use the subscript form to access the contents of the array.

const buf = Buffer.from([1, 2, 3, 4, 5]);
console.log(buf[0]); // 1
console.log(buf[5]); // undefined

They will parse bytes in complement form and return the corresponding number.

readXxx

We can also pass

buf.readInt8() buf.readInt16() buf. readUint8() buf.readUint16() and other methods to access the content in the Buffer object.

const buf = Buffer.from([1, 2, 3, 4, 5]);
console.log(buf.readInt8(2)); // 3

// 访问超出范围的内容,会抛出 RangeError
console.log(buf.readInt8(5)); // RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range.

Iterator

The iterator of the Buffer object is the same as the iterator of the array. There are also three iterators, which are

    entries
  • keys
  • #values
We access the contents of the Buffer object by traversing the iterator.

const buf = Buffer.from([3, 4, 2]);

for (let entry of buf.entries()) {
  // 数组的一个元素为下标,第二个元素为下标对应的元素
  console.log(entry); // [ 0, 3 ]
                      // [ 1, 4 ]
                      // [ 2, 2 ]
}
for (let key of buf.keys()) {
  console.log(key); // 0
                    // 1
                    // 2
}
for (let value of buf.values()) {
  console.log(value); // 3
                      // 4
                      // 2
}

Writing Buffer Object

This section explains how to write content to the Buffer object.

Subscript

We can change the contents of the Buffer object directly through the subscript

const buf = Buffer.from([1, 2, 3]);

// 通过下标设置值
buf[0] = 4;

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

write

We can write a string to the Buffer through the

write(string, [offset], [length], [encoding]) method:

    string: indicates the The written string
  • offset: offset, that is, skip offset bytes to start writing, the default is 0
  • length: the maximum number of bytes to be written, no more than
  • buf.length - offset, the default value is buf.length - offset
  • encoding: Specify the encoding, the default is
  • utf-8
This method returns the number of bytes written.

const buf = Buffer.from([1, 2, 3, 4]);

// 跳过 1 个字节开始写入,1hi4
buf.write("hi", 1);

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

writeXxx

Same as readXxx, we can write data to buf through the

writeInt8() method, which receives two parameters:

  • value:要写入的值
  • offset:偏移量,默认为 0
const buf = Buffer.alloc(5);

buf.writeInt8(1, 0);
buf.writeInt8(3, 1);

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

踩坑:没有 writeInt16(),不过有 writeInt16BE()writeInt16LE(),分别代表以大端序、小端序写入。

其他方法

isBuffer

该方法接收一个对象,用来判断该对象是不是一个 Buffer 对象

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

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

isEncoding

该方法接收一个代表编码的字符串,返回 Buffer 是否支持该种编码,如果支持则返回 true,否则返回 false

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

slice

slice(start, end) 可以裁切原有的 Buffer 对象,返回一个新的 Buffer 对象,其中 start 和 end 代表裁切的起始位置和结束位置,左闭右开 [start, end),这两个参数是可选的,start 默认为 0,end 默认为 buf.length。返回的 Buffer 对象与原先对象引用的是同一块内存,即它们的 buffer 属性是一样的。

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

const newBuffer = buffer.slice(6); // 裁切 6 以后的内容到新数组
console.log(newBuffer.toString()); // world!

console.log(buffer.buffer === newBuffer.buffer); // true

subarray

subarray(start, end) 几乎可以看做等同于 slice 方法了,二者的语义不同,不过行为确实一致的,subarray 的语义表示返回原数组的某个范围的子数组,而 slice 的语义表示的裁切。同样 subarray 返回新的 Buffer 对象,并且返回的 Buffer 对象的 buffer 与原 Buffer 对象的 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

copy(target, [targetStart], [sourceStart], [sourceEnd]) 方法是将 source 从 sourceStart 到 sourceEnd 的内容复制到 target 从 targetStart 的位置,见下动图

Detailed explanation of the operations of Buffer objects in Node.js (creation, reading and writing)

除了 target 以外,其他三个参数都是可选参数,targetStart 与 sourceStart 的默认值为 0,sourceEnd 的默认值为 buf.length.

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

buf1.copy(buf2, 0, 1, 9);

console.log(buf2.toString()); // elloWorl

includes

buf.includes(value, [offset], [encoding]) 方法的作用是判断 value 是否在 buf 中。

value 可以是一个字符串,也可以是一个 Buffer 对象,也可以是一个整数;offset 用来规定查找范围,表示从 offset 处开始查找,默认为 0;enconding 表示编码,默认为 utf-8

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

// 默认从 0 开始搜索
console.log(buf.includes("H")); // true
// 从 1 开始搜索,后面不包含 H
console.log(buf.includes("H", 1)); // false

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

// H 对应的 utf-8 编码为 72
console.log(buf.includes(72)); // true

indexOf

buf.indexOf(value, [offset], [encoding]) 是用来查找 value 在 buf 中的下标的,参数的含义同 includes 方法相同,如果在 buf 找不到 value,那么会返回 -1,所以 includes(value) 方法其实就相当于 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

equals

buf.equals(otherBuffer) 是比较两个 Buffer 对象的字节是否完全相同,如果相同,则返回 true,否则返回 false

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

更多node相关知识,请访问:nodejs 教程!!

The above is the detailed content of Detailed explanation of the operations of Buffer objects in Node.js (creation, reading and writing). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete