nodejs article Buffer module

foreword

insert image description here

The Buffer object is an interface for Node to process binary data. It is a global object natively provided by Node and can be used directly without require('buffer').

JavaScript is better at processing strings, but not so good at processing binary data (such as TCP data streams). The Buffer object is designed to solve this problem. It is a constructor, and the generated instance represents a section of memory allocated by the V8 engine. It is an array-like object, and its members are integer values ​​from 0 to 255, that is, an 8-bit byte.

nodejs commonjs introduces
nodejs fs module introduces
nodejs path module introduces
nodejs events module introduces
nodejs http module introduces
nodejs net module introduces
nodejs url module introduces
nodejs process module

basic use

Create a buffer data.

new Buffer()

var bin = new Buffer([0x68, 0x65, 0x6c, 0x6c, 0x6f]);
// 第一个参数是buffer的内容,第二个参数则是buffer采用的编码方式。 即将废弃
var bin2 = new Buffer("hello", "utf-8");
console.log(bin[0]); // 104
console.log(bin.length); // 5
var str = bin.toString("utf-8");
console.log(str); // hello

Buffer.from()

// 第一个参数是buffer的内容,第二个参数则是buffer采用的编码方式,第二个参数默认是utf8。用Buffer.from 取代new Buffer
onst buf = Buffer.from("hello world", "utf8");
var str1 = buf.toString("utf-8");
console.log(str1); // hello world
const buf1 = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
var str2 = buf1.toString("utf-8");
console.log(str2); // buffer

Common attributes on Buffer instance buf

buf[index],buf.length

var bin = new Buffer([0x68, 0x65, 0x6c, 0x6c, 0x6f]);
console.log(bin[0]); // 104
console.log(bin.length); // 5

Common methods on Buffer instance buf

buf.write()

The write method can write data to the specified Buffer object. Its first parameter is the content to be written, the second parameter (can be omitted) is the starting position of the writing (default starts from 0), the third parameter (can be omitted) is the encoding method, the default is utf8.

var buff1 = new Buffer(40);
buff1.write("dengxi");
buff1.write("age", 20);
buff1.write("18", 30);
console.log(buff1.toString()); // dengxiage18

buf.slice()

The slice method does not return a new Buffer. If the returned buffer changes, the original buffer will also change.

var buff2 = new Buffer("just some data");
var chunk = buff2.slice(5, 9);
chunk[0] = 0x65;
console.log(chunk.toString()); // eome
console.log(buff2.toString()); // just eome data

buf.toString()

The first parameter is the specified encoding, the second parameter is the starting position, and the third parameter is the ending position (but not including the ending position)

var hello = new Buffer("Hello");
hello; // <Buffer 48 65 6c 6c 6f>
hello.toString(); // "Hello" 
var a = hello.toString("ascii", 1, 4);
console.log(a); //ell

buf.toJSON()

into a JSON string

var test = new Buffer("test");
var json = test.toJSON();
console.log(json); // '[116,101,115,116]'
var json1 = test.toJSON(); // { type: 'Buffer', data: [ 116, 101, 115, 116 ] }

buf.copy()

If you want to copy a Buffer data, you must first create a new Buffer, and copy the data in the original Buffer through the .copy method

var bin1 = new Buffer([0x68, 0x65, 0x6c, 0x6c, 0x6f]);
var dup1 = new Buffer(bin.length);

bin1.copy(dup1);
dup1[0] = 0x48;
console.log(bin1); // => <Buffer 68 65 6c 6c 6f>
console.log(dup1); // => <Buffer 48 65 65 6c 6f>

buf.compare()

The function syntax of the comparison compares the relative positions of the two buffers, and judges the relative positions of the two buffers by the size of the return value (with 0 as the boundary).

var buffer1 = new Buffer("ABC");
var buffer2 = new Buffer("ABCD");
var result = buffer1.compare(buffer2);
if (result < 0) {
    
    
  console.log(buffer1 + " 在 " + buffer2 + "之前");
} else if (result == 0) {
    
    
  console.log(buffer1 + " 与 " + buffer2 + "相同");
} else {
    
    
  console.log(buffer1 + " 在 " + buffer2 + "之后");
} // ABC 在 ABCD之前

buf.kys() buf.entries() buf.values()

Similar to these three methods of Object

var buffer3 = new Buffer([0x68, 0x65, 0x6c, 0x6c, 0x6f]);
for (const item of buffer3.entries()) {
    
    
  console.log(item);
}
/** 
 * [ 0, 104 ]
[ 1, 101 ]
[ 2, 108 ]
[ 3, 108 ]
[ 4, 111 ]
 * */

for (const item of buffer3.values()) {
    
    
  console.log(item);
}
//   104 101 108 108 111

for (const key of buffer3.keys()) {
    
    
  console.log(key);
}
// 0 1 2 3 4

buf.equals()

Check if two buffers are the same.

const a1 = Buffer.from("hello");
const b1 = Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]);

console.log(a1.equals(b1)); // true

buf.indexOf(value[, byteOffset][, encoding]) 和 buf.lastIndexOf(value[, byteOffset][, encoding])

const c1 = Buffer.from("this is a buffer");
console.log(c1.indexOf("this")); // 0
console.log(c1.indexOf("is")); // 2
console.log(c1.lastIndexOf("is")); // 5
console.log(c1.indexOf("bb")); // -1

buf.includes(value[, byteOffset][, encoding])

const d1 = Buffer.from("this is a buffer");
console.log(d1.includes("this")); // true

buf.fill(value[, offset[, end]][, encoding])

You can modify the already created buf, but you need to pay attention not to exceed the byte range specified by buf, otherwise an error will be reported

const e1 = Buffer.allocUnsafe(10).fill("h");
console.log(e1.toString()); // hhhhhhhhhh

const f1 = new Buffer(10);
f1.fill("a", 1, 5, "utf8");

console.log(f1.toString()); //aaaa

Methods of the Buffer class

Buffer.isEncoding()

Determine whether the encoding method exists

console.log(Buffer.isEncoding("hex")); //true
console.log(Buffer.isEncoding("utf8")) // true
console.log(Buffer.isEncoding("utf81")) // false

Buffer.concat()

To connect multiple buffers, the Buffer.concat method merges a group of Buffer objects into one Buffer object.

var i1 = new Buffer("Hello");
var i2 = new Buffer(" ");
var i3 = new Buffer("World");
var i4 = Buffer.concat([i1, i2, i3]).toString();
console.log(i4); // Hello World

Buffer.byteLength()

count bytes

Buffer.byteLength("Hello", "utf8"); // 5
var i7 = new Buffer("Hello1")
console.log(Buffer.byteLength(i7))  // 6

Buffer.isBuffer()

To judge whether the buffer data

Buffer.isBuffer(new Date()); // false
Buffer.isBuffer(new Buffer(2)); // true

Buffer.alloc(size[, fill[, encoding]])

Allocate a new buffer, which can also be used to create new buffer data

const g1 = Buffer.alloc(5, "d", "utf8");
console.log(g1); // <Buffer 64 64 64 64 64>

Guess you like

Origin blog.csdn.net/glorydx/article/details/129028155