What is the Node.js buffer.equals() method?

If we want to check if two buffer objects are equal, we can use buffer.equals() method. It will return true if both buffer objects have the same bytes. Otherwise, it will return false.

Syntax

buffer.equals(buf)

Parameters

It takes buffer as the parameter.

Return value

The return value is Boolean.

Example 1

This example returns true because buf1 and buf2 have the same bytes.

const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('ABC');
console.log(buf1.equals(buf2));

Example 2

This example returns false because both buf1 and buf2 have different bytes.

const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('abc');
console.log(buf1.equals(buf2));

Example 3

This returns true because buf1 and buf2 have the same bytes.

The fills may look different in both buffers, but when they are converted as buffers they will have the same bytes.

Uncomment to log the buffers into the console in the code snippet below.

const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('414243', 'hex');
// console.log(buf1);
// console.log(buf2);
console.log(buf1.equals(buf2));

Free Resources