About node JS Buffer

The JavaScript language itself has only string data types and no binary data types.

However, binary data must be used when processing such as TCP stream or file stream. Therefore, in node JS, a Buffer class is defined, which is used to create a cache for storing binary data.

On Node JS, the Buffer class is a core library published with the Node kernel. The Buffer library is Node JS brings a method to store raw data, which can make Node JS handles binary data whenever needed in Node When processing data moved in I/O operations in JS, it is possible to use Buffer library.

The raw data is stored in an instance of the Buffer class.

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

Create Buffer class

The Node Buffer class can be created in many ways.

Method 1

Create a Buffer instance with a length of 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 through a string:

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

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

Write buffer

grammar

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

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

parameter

The parameters are described as follows:

  • String - the string to write to the buffer.
  • offset - the index value that the buffer starts to write. The default value is 0.
  • Length - the number of bytes written. The default is buffer length
  • Encoding - the encoding used. The default is' utf8 '.

Return value

Returns the size of the actual write. If the buffer space is insufficient, only part of the string will be written.
example

buf = new Buffer(256);
len = buf.write("bi");
len = buf.write("bianchengsanmei");

console.log("Number of bytes written : "+  len);

Execute the above code and the output result is:

$node main.js
 Number of bytes written : 15

Read data from buffer

grammar

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 used. The default is' utf8 '.

  • Start - specifies the index position to start reading. The default is 0.

  • End - the end position, which defaults to the end of the buffer.

Return value

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

example

buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
  buf[i] = i + 97;
}

console.log( buf.toString('ascii'));       // Output: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5));   // Output: abcde
console.log( buf.toString('utf8',0,5));    // Output: abcde
console.log( buf.toString(undefined,0,5)); // Use 'utf8' encoding and output: abcde

Execute the above code and the output result is:

$ node main.js
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde

Convert Buffer to JSON object

grammar

The function syntax format of converting Node Buffer into JSON object is as follows:

buf.toJSON()

Return value

Return JSON object.

example

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

console.log(json);

Execute the above code and 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

grammar

The syntax of Node buffer merging is as follows:

Buffer.concat(list[, totalLength])

parameter

The parameters are described as follows:

  • List - a list of Buffer object arrays used for merging.
  • totalLength - specifies the total length of the merged Buffer object.

Return value

Returns a new Buffer object with multiple members merged.

example

var buffer1 = new Buffer('Programming samadhi ');
var buffer2 = new Buffer('bi');
var buffer2 = new Buffer('bianchengsanmei');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 content: " + buffer3.toString());

Execute the above code and the output result is:

buffer3 content: Programming samadhi bianchengsanmei

Buffer comparison

grammar

The function syntax of Node Buffer comparison is as follows. This method is in node js v0. 12.2 version introduction:

buf.compare(otherBuffer);

parameter

The parameters are described as follows:

  • otherBuffer - another Buffer object compared with the Buffer object.

Return value

Returns a number indicating that the buffer is before, after or the same as otherBuffer.

example

var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('ABCD');
var result = buffer1.compare(buffer2);

if(result < 0) {
   console.log(buffer1 + " stay " + buffer2 + "before");
}else if(result == 0){
   console.log(buffer1 + " And " + buffer2 + "identical");
}else {
   console.log(buffer1 + " stay " + buffer2 + "after");
}

Execute the above code and the output result is:

ABC stay ABCD before

Copy Buffer

grammar

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

No return value.

example

var buffer1 = new Buffer('ABC');
// Copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());

Execute the above code and 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 block of memory as the old buffer, but is clipped from the index start to end.

example

var buffer1 = new Buffer('youj');
// Clipping buffer
var buffer2 = buffer1.slice(0,2);
console.log("buffer2 content: " + buffer2.toString());

Execute the above code and 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.

example

var buffer = new Buffer('bianchengsanmei');
//  Buffer length
console.log("buffer length: " + buffer.length);

Execute the above code and the output result is:

buffer length: 15

~

~End of this article, thank you for reading!

~

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

Hello, I'm Programming samadhi Hermit Wang, my official account is " Programming samadhi "Welcome to pay attention and hope you can give us more advice!

You come, with expectations, I have ink to greet you! You return, no matter gain or loss, only with the rhyme!

Pay equal attention to knowledge and skills, cultivate both internal and external skills, grasp both theory and practice, and be hard on both hands!

Keywords: Javascript node.js

Added by Jiraiya on Wed, 26 Jan 2022 15:16:57 +0200