Assert Module in Node.js


The assert module provides a bunch of different functionalities that are used for function assertion. This module provides these functions for verifying invariants in a program. We can use assertion for a null check or different other checks. The assertion does not impact any running implementation. It only checks the condition and throws an error if the error is not satisfied.

Installing the Assert Module

npm install assert

The assert module is an inbuilt Node.js module, so you can skip this step as well.

Importing the module in your function

const assert = require("assert");

Example

 Live Demo

const assert = require('assert');
let x = 3;
let y = 21;
assert(x>y);

Output

C:\home
ode>> node assert.js assert.js:339    throw err;    ^ AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:    assert(x>y)       at Object. (/home/node/mysql-test/assert.js:6:1)       at Module._compile (internal/modules/cjs/loader.js:778:30)       at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)       at Module.load (internal/modules/cjs/loader.js:653:32)       at tryModuleLoad (internal/modules/cjs/loader.js:593:12)       at Function.Module._load (internal/modules/cjs/loader.js:585:3)       at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)       at startup (internal/bootstrap/node.js:283:19)       at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Example

Let's take a look at one more example. In the above program, we are not handling the error. We are telling the system to handle that error for us. Therefore, it prints all the system logs. In this example, we will handle any error using a try() & catch() block.

const assert = require('assert');

let x = 3;
let y = 21;

try {
   // Checking the condition...
   assert(x == y);
}
catch {
   // Printing the error if it occurs
   console.log(
      `${x} is not equal to ${y}`);
}

Output

C:\home
ode>> node assert.js 3 is not equal to 21

Updated on: 20-May-2021

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements