How to exit a process in Node.js?

Node.jsServer Side ProgrammingProgramming

There are some cases where we need to exit a certain process in Node.js based upon a condition. For this condition, we have the following methods where we can escape or exit any Node.js Process.

Method 1: Using the Ctrl+C key

I hope everyone knows this shortcut to exit any Node.js process from outside. This shortcut can be used to stop any running process by hitting this command on terminal.

Method 2: Using the process.exit() function

This function instructs Node.js to end the process that is running at an instant with an exit code. Node.js will force the current running process to stop execution as soon as it encounters this statement.

Syntax

process.exit(code)

The code here defines the value of code which can either be 0 or 1. "0" represents the end of process without any failure, whereas "1" represents end of the process with some failure.

Example 1

// Initializing an empty array
var arr = [];
var a=2, b=8;

// Running the loop infinitely
while (a < 10 || b < 10) {
   // Incrementing the value of a&b
   a = a + 1;
   b = b + 2;

   // Pushing the sum into array
   arr.push(a + b);

   // Process will be exited when a & b becomes equal
   if (a > 2 && b>4) {
      console.log("Exiting since a>2 & b>4");
      process.exit(0);
      console.log("Process exited successfully")
   }
}

Output

C:\home\node>> node exit.js
Exiting since a>2 & b>4

Method 3 - Using the process.on() function

This Process is a global object in Node.js. It automatically exits the process when it reaches the end of line in code. We can use the process.on function to exit any process in Node.js.

Syntax

process.on()

Example 2

console.log('Welcome to TutorialsPoint !');

process.on('exit', function (code) {
   return console.log(`Process to exit with code ${code}`);
});

Output

C:\home\node>> node exit.js
Welcome to TutorialsPoint !
Process to exit with code 0
raja
Published on 17-Jan-2022 11:39:11

Advertisements