• Node.js Video Tutorials

Node.js - Buffer.equals() Method



The NodeJS Buffer.equals() compares two buffers and returns true if it's equal and false if not. It is somewhat similar to the method Buffer.compare() when it returns 0.

Syntax

Following is the syntax of the NodeJS equals() method −

buffer.equals(buf);

Parameters

The method Buffer.equals() takes in a single parameter which is also a buffer. It is a mandatory param.

  • buf −It is a buffer object which is used to compare.

Return value

The Buffer.equals() return true if the buffer compared is equal and false if it is not.

Example

In the below example we have created two buffers having the string "Hello". Later both buffers are compared using the NodeJS buffer.equal() method.

const buffer1 = Buffer.from('Hello');
const buffer2 = Buffer.from('Hello');
console.log("The output for buffer.equals() is "+buffer1.equals(buffer2));

Output

The output for buffer.equals() is true

Example

In the below example we have created two buffers having the string "Hello" and "World". Later both buffers are compared using the buffer.equal() method. Since the strings are not the same the output from buffer.equals() will be false.

const buffer1 = Buffer.from('Hello');
const buffer2 = Buffer.from('World');
console.log("The output for buffer.equals() is "+buffer1.equals(buffer2));

Output

The output for buffer.equals() is false

Example

In the example below we have used buffer.equals and buffer.compare() methods to compare the result if the string is the same.

const buffer1 =  Buffer.from("hello");
var buffer2 = Buffer.from("hello");
buffer1.equals(buffer2);  // It will return true
buffer1.compare(buffer2); // It will return 0
Buffer.compare(buffer1, buffer2);// It will return 0
console.log("Using Buffer.equals() "+ buffer1.equals(buffer2));
console.log("Using Buffer.compare() "+ buffer1.compare(buffer2));

Output

Using Buffer.equals() true
Using Buffer.compare() 0

Example

The method buffer.equals() is case sensitive. It means the string Hello and hello are different.

const buffer1 = Buffer.from('Hello');
const buffer2 = Buffer.from('hello');
console.log("The output for buffer.equals() is "+buffer1.equals(buffer2));

Output

The output for buffer.equals() is false

Example

In the example we have two buffers one having string Hello, and hex code values of string Hello: 48656c6c6f

Now when we compare both the buffers it will return true.The reason being the space allocated for both will be same.

const buffer1 = Buffer.from('Hello');
const buffer2 = Buffer.from('48656c6c6f', 'hex');
console.log("The output for buffer.equals() is "+buffer1.equals(buffer2));

Output

The output for buffer.equals() is true
nodejs_buffer_module.htm
Advertisements