头图

The JavaScript language itself only has a string data type, not a binary data type.

But when dealing with streams like TCP or file streams, binary data must be used. Therefore, in Node.js, a Buffer class is defined, which is used to create a buffer area dedicated to storing binary data.

In Node.js, the Buffer class is the core library that ships with the Node kernel. The Buffer library brings to Node.js a way to store raw data, allowing Node.js to work with binary data, it is possible to use the Buffer library whenever data moving in I/O operations needs to be processed in Node.js .

Raw data is stored in an instance of the Buffer class.

A Buffer is similar to an array of integers, but it corresponds to a piece of raw memory outside of the V8 heap memory.

Create the Buffer class

The Node Buffer class can be created in a number of ways.

Method 1

Create a Buffer instance of length 10 bytes:

var buf = new Buffer(10);

Method 2

Create a Buffer instance from the given array:

var buf = new Buffer([10, 20, 30, 40, 50]);

Method 3

Create a Buffer instance from a string:

var buf = new Buffer("bianchengsanmei", "utf-8");

utf-8 is the default encoding, and it also supports the following encodings: "ascii", "utf8", "utf16le", "ucs2", "base64" and "hex".

write buffer

Syntax

The syntax for writing to a Node buffer is as follows:

buf.write(string[, offset[, length]][, encoding])

parameter

The parameters are described as follows:

  • string - String to write to buffer.
  • offset - The index value at which to start writing to the buffer, defaults to 0.
  • length - number of bytes written, default is buffer.length
  • encoding - The encoding used. Defaults to 'utf8'.

return value

Returns the size actually written. If the buffer space is insufficient, only part of the string will be written.
instance

buf = new Buffer(256);
len = buf.write("bi");
len = buf.write("bianchengsanmei");
 
console.log("写入字节数 : "+  len);

Execute the above code, the output result is:

$node main.js
写入字节数 : 15

read data from buffer

Syntax

The syntax for reading Node buffer data is as follows:

buf.toString([encoding[,start[,end]]])

parameter

The parameters are described as follows:

  • encoding - the encoding to use. Defaults to 'utf8'.
  • start - Specifies the index position to start reading, defaults to 0.
  • end - the end position, defaults to the end of the buffer.

return value

Decodes buffer data and returns a string using the specified encoding.

instance

buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
  buf[i] = i + 97;
}
 
console.log( buf.toString('ascii'));       // 输出: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5));   // 输出: abcde
console.log( buf.toString('utf8',0,5));    // 输出: abcde
console.log( buf.toString(undefined,0,5)); // 使用 'utf8' 编码, 并输出: abcde

Execute the above code, the output result is:

$ node main.js
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde

Convert Buffer to JSON object

syntax

The function syntax format for converting Node Buffer to JSON object is as follows:

buf.toJSON()

return value

Returns a JSON object.

instance

var buf = new Buffer('bianchengsanmei');
var json = buf.toJSON(buf);
 
console.log(json);

Execute the above code, the output result is:

{ type: 'Buffer',
  data: [ 119, 119, 119, 46, 119, 51, 99, 115, 99, 104, 111, 111, 108, 46, 99, 110 ] }

buffer merge

Syntax

The syntax for Node buffer coalescing is as follows:

Buffer.concat(list[, totalLength])

parameter

The parameters are described as follows:

  • list - a list of arrays of Buffer objects to merge.
  • totalLength - Specifies the total length of the merged Buffer objects.

return value

Returns a new Buffer object with multiple members merged.

instance

var buffer1 = new Buffer('编程三昧 ');
var buffer2 = new Buffer('bi');
var buffer2 = new Buffer('bianchengsanmei');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 内容: " + buffer3.toString());

Execute the above code, the output result is:

buffer3 内容: 编程三昧 bianchengsanmei

buffer comparison

syntax

The function syntax for Node Buffer comparison is as follows, which was introduced in Node.js v0.12.2:

buf.compare(otherBuffer);

parameter

The parameters are described as follows:

  • otherBuffer - Another Buffer object to compare with the buf

return value

Returns a number representing buf in otherBuffer before, or after the same.

instance

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 + "之后");
}

Execute the above code, the output result is:

ABC在ABCD之前

copy buffer

Syntax

The Node buffer copy syntax is as follows:

buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])

parameter

The parameters are described as follows:

  • targetBuffer - the Buffer object to copy.
  • targetStart - number, optional, default: 0
  • sourceStart - number, optional, default: 0
  • sourceEnd - number, optional, default: buffer.length

return value

There is no return value.

instance

var buffer1 = new Buffer('ABC');
// 拷贝一个缓冲区
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());

Execute the above code, the output result is:

buffer2 content: ABC

buffer clipping

The Node buffer clipping syntax is as follows:

buf.slice([start[, end]])

parameter

The parameters are described as follows:

  • start - number, optional, default: 0
  • end - number, optional, default: buffer.length

return value

Returns a new buffer that points to the same memory as the old buffer, but is cut from index start to end.

instance

var buffer1 = new Buffer('youj');
// 剪切缓冲区
var buffer2 = buffer1.slice(0,2);
console.log("buffer2 content: " + buffer2.toString());

Execute the above code, the output result is:

buffer2 content: yo

buffer length

syntax Node Buffer length calculation syntax is as follows:

buf.length;

return value

Returns the length of memory occupied by the Buffer object.

instance

var buffer = new Buffer('bianchengsanmei');
//  缓冲区长度
console.log("buffer length: " + buffer.length);

Execute the above code, the output result is:

buffer length: 15

~

~End of this article, thanks for reading!

~

Learn interesting knowledge, meet interesting friends, and shape interesting souls!

Hello everyone, I am King , the author Programming Samadhi 〗, my is "161f6a0f4b4476 Programming Samadhi ", welcome to pay attention, I hope you can give me more advice!

You come, with expectations, I have the fragrance of ink to welcome you! You return, no matter what you gain or lose, you can only give it away with the aftertaste!

Both knowledge and skills are emphasized, internal and external skills are cultivated, both theory and practice must be grasped, and both hands must be hard!


编程三昧
54 声望10 粉丝

学习有趣的知识,交识有趣的朋友,造就有趣的灵魂!