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');, buf2); // 0, means the 2 buffers are equal, buf3); // 1, means buf1 < buf3

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

const isEqual =, buf2) === 0;


The function returns:

This means you can use when sorting an array of buffers. orders buffers lexicographically, so, for buffers containing utf8 strings, sorting using 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(; => buf.toString('utf8')); // ['A', 'B', 'C']

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

More Node Tutorials