• Node.js Video Tutorials

Node.js - Buffer.compare() Method



The NodeJS Buffer.compare() method helps in comparing two given buffer objects and returns a value that states the difference in comparison. One good use of the Buffer.compare() method is to sort arrays that contain buffers.

Syntax

Following is the syntax of the Node.JS Buffer.compare() Method −

Buffer.compare(buf1, buf2)

Parameters

This method accepts two parameters. The same is explained below.

  • buf1 −(required) A buffer object.

  • buf2 −(required). A buffer object.

Return value

The Buffer.compare() method returns a number that tells about the comparison of two buffers. The number returned will be as follows −

  • 0 if the buffer objects are equal,

  • 1 if the first buffer object is greater than the second buffer object.

  • -1 if the first buffer object is less than the second buffer object.

Example

The example will create two buffers and compare them.

const buffer1 = Buffer.from('test');
const buffer2 = Buffer.from('test');
const result = Buffer.compare(buffer1, buffer2);
console.log("The result is :"+result);

Output

The result is :0

Example

The example will create two buffers in which buffer 1 will be lower than buffer2 and should give result a -1. Another example in which buffer1 will be greater than buffer2. So the result has to be 1.

const buffer1 = Buffer.from('A');
const buffer2 = Buffer.from('B');
const result = Buffer.compare(buffer1, buffer2);
console.log("The result is :"+result);
const buffer11 = Buffer.from('B');
const buffer21 = Buffer.from('A');
const result1 = Buffer.compare(buffer11, buffer21);
console.log("The result is :"+result1);

Output

The result is :-1
The result is :1

Example

In this example we will see how we can make use of the Buffer.compare() method in sorting an array of buffers.

const buffer1 = Buffer.from('How');
const buffer2 = Buffer.from('Are');
const buffer3 = Buffer.from('You');
var myarray = [buffer1, buffer2, buffer3];
console.log(myarray);
console.log(myarray.sort(Buffer.compare).toString());

Output

[ <Buffer 48 6f 77>, <Buffer 41 72 65>, <Buffer 59 6f 75> ]
Are,How,You
Advertisements