Open In App

Node.js Buffer.compare() Method

Buffer is a temporary memory storage that stores the data when it is being moved from one place to another. It is like an array of integers. Buffer.compare() method compares the two given buffers. 

Syntax:



buffer1.compare( targetBuffer, targetStart,
            targetEnd, sourceStart, sourceEnd )

Parameters: This method accepts five parameters as mentioned above and described below:

Return Value: It returns a number indicating the difference in both buffers. The returns number are:



Example 1: The below example illustrates the Buffer.compare() Method in Node.js: 




// Node.js program to demonstrate the
// Buffer.compare() Method
 
// Creating a buffer
const buffer1 = Buffer.from('Geek');
const buffer2 = Buffer.from('Geek');
const op = Buffer.compare(buffer1, buffer2);
console.log(op);
 
const buffer1 = Buffer.from('GFG');
const buffer2 = Buffer.from('Python');
const op = Buffer.compare(buffer1, buffer2);
console.log(op);

Output: 

0
-1

Example 2: The below example illustrates the Buffer.compare() Method in Node.js: 




// Node.js program to demonstrate the
// Buffer.compare() Method
 
// Creating a buffer
const buffer1 = Buffer.from('2');
const buffer2 = Buffer.from('1');
const buffer3 = Buffer.from('3');
const array = [buffer1, buffer2, buffer3];
 
// Before sorting
console.log(array);
 
// After sorting array
console.log(array.sort(Buffer.compare));

Output:

[ <Buffer 32>, <Buffer 31>, <Buffer 33> ]
[ <Buffer 31>, <Buffer 32>, <Buffer 33> ]

Example 3: The below example illustrates the Buffer.compare() Method in Node.js: 




// Node.js program to demonstrate the
// Buffer.compare() Method
 
const buffer1 = Buffer.from('GeeksOne');
const buffer2 = Buffer.from('GeekTwo');
 
// Print: -1 as size of buffer1 starting
// from index 4 is less than buffer2 size
let op = buffer1.compare(buffer2, 4);
 
// Print: 1 as the size of buffer2 starting
// from index 5 is less than size of buffer1
// starting from 0th index
let op1 = buffer1.compare(buffer2, 0, 7, 5);
 
console.log(op);
console.log(op1);

Output:

-1
1

Note: The above program will compile and run by using the node index.js command. 

Reference: https://nodejs.org/api/buffer.html#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend


Article Tags :