Compare Two Buffers in Node.js

Aug 17, 2020

Node.js buffers are objects that store arbitrary binary data. They're Node's equivalent to blobs.

Comparing two buffers is easy. Node.js' Buffer class has a static function compare() that returns 0 if two buffers are equal.

const buf1 = Buffer.from('Hello, World', 'utf8');
const buf2 = Buffer.from('Hello, World', 'utf8');
const buf3 = Buffer.from('Different buffer', 'utf8');

Buffer.compare(buf1, buf2); // 0, means the 2 buffers are equal

Buffer.compare(buf1, buf3); // 1, means buf1 < buf3

That means, to check if buf1 has the same bytes as buf2, you can do:

const isEqual = Buffer.compare(buf1, buf2) === 0;

Sorting

The Buffer.compare() function returns:

This means you can use Buffer.compare() when sorting an array of buffers. Buffer.compare() orders buffers lexicographically, so, for buffers containing utf8 strings, sorting using Buffer.compare() is equivalent to sorting by the string representation of the buffer.

const buffers = [
  Buffer.from('A', 'utf8'),
  Buffer.from('C', 'utf8'),
  Buffer.from('B', 'utf8')
];

buffers.sort(Buffer.compare);

buffers.map(buf => buf.toString('utf8')); // ['A', 'B', 'C']

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Node Tutorials