Node.js Buffer compare

Introduction

Following is the syntax of the method to compare two Node buffers:

buf.compare(otherBuffer);

Returns a number indicating whether this comes before or after or is the same as the otherBuffer in sort order.

// example// w  ww.j  a v a  2 s  . c  om
var buffer1 = Buffer.from('ABC');
var buffer2 = Buffer.from('ABCD');
var result = buffer1.compare(buffer2);

if(result < 0) {
   console.log(buffer1 +" comes before " + buffer2);
}else if(result == 0){
   console.log(buffer1 +" is same as " + buffer2);
}else {
   console.log(buffer1 +" comes after " + buffer2);
}

//Buffer comparison
var buffer1 = Buffer.from('sample buffer1');
var buffer2 = Buffer.from('sample buffer2');
var result = buffer1.compare(buffer2);
if (result > 0) {
    console.log(buffer1 + 'comes before' + buffer2);
} else if (result == 0) {
    console.log('Both are equal');
} else {
    console.log(buffer1 + 'comes after' + buffer2);
}



PreviousNext

Related