GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Check if a File Exists in Node.js
  • Working with UUID in Node
  • Using bcrypt-js to Hash Passwords in JavaScript
  • Working with the Node.js assert Library
  • Modify Authorized redirect_uris For Google OAuth
  • Fundamentals
  • Node
  • Vue
  • Webpack
  • Axios
  • Mongoose
  • Express
  • Lodash
  • npm

This view

  • Original page
  • New address

GeezerVison is showing masteringjs.io — Compare Two Buffers in Node.js

Mastering JS Logo
Mastering JS
Tutorials Newsletter eBooks Jobs
☰
Tutorials Newsletter eBooks Jobs
Tutorials / Node /

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:

  • 0 if buf1 and buf2 are equal
  • 1 if buf1 < buf2
  • -1 if buf1 > buf2

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

  • Getting Started with Oso Authorization in Node.js
  • Check if a File Exists in Node.js
  • How To Fix "__dirname is not defined" Error in Node.js
  • Working with UUID in Node
  • Using bcrypt-js to Hash Passwords in JavaScript
  • Working with the Node.js assert Library
  • Modify Authorized redirect_uris For Google OAuth
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.