Buffer.compare() in nodejs

Arun Rajeevan
2 min readJun 18, 2020

--

Buffer.compare(buf1, buf2) or buf1.compare(buf2)

Type of buf1 and buf2 is Buffer,specifically Uint8Array
Returns -1,0,1, depending on the result of the comparison.

  • 0 is returned if buf1 is the same as buf2
  • 1 is returned if buf2 should come before buf1 when sorted.
  • -1 is returned if buf2 should come after buf1 when sorted.
const buf1 = Buffer.from('1234');
const buf2 = Buffer.from('0123');
const arr = [buf1, buf2];
console.log(arr.sort(Buffer.compare));
// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
// (This result is equal to: [buf2, buf1].)

considering the line in above example,
// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ], this because the UTF-8 value of Zero is 30.

To understand the comparison, you must know how strings are stored in Buffer? What is Utf-8 format?

Refer link: http://www.fileformat.info/info/charset/UTF-8/list.htm
for complete list of Utf-8 code for characters

For more info about UTF encoding: https://www.w3schools.com/charsets/ref_html_utf8.asp

Sample is given below for UTF-8 characters and values:

Example 1:

var buffer1 = Buffer.from(‘Geek’);
var buffer2 = Buffer.from(‘Geek’);
var op = Buffer.compare(buffer1, buffer2);
console.log(op);

Output will be 0

Example 2:

var buffer1 = Buffer.from(‘GFG’);
var buffer2 = Buffer.from(‘Python’);
var op = Buffer.compare(buffer1, buffer2);
console.log(op);

Output will be -1

Example 3:

var buffer1 = Buffer.from(‘GFG’);
var buffer2 = Buffer.from(‘P’);
var op = Buffer.compare(buffer1, buffer2);
console.log(op);

Output will be -1

Example 4:

var buffer1 = Buffer.from(‘GFG1’);
var buffer2 = Buffer.from(‘GFG’);
var op = Buffer.compare(buffer1, buffer2);
console.log(op);

Output will be 1

Example 5:

var buffer1 = Buffer.from(‘GFG’);
var buffer2 = Buffer.from(‘GFG1’);
var op = Buffer.compare(buffer1, buffer2);
console.log(op);

Output will be -1

--

--

No responses yet