Understanding the Exit Process in Node.js

In this article, we’ll explore a basic Node.js concept that allows your application to keep running indefinitely. We’ll learn how to use a simple setInterval function to simulate a process that continues to execute until it’s manually terminated. If you’ve ever wondered how to keep your Node.js program alive until you decide to stop it, this tutorial is for you

 

We Have 3 Methods to exit from Node.js application :

  1. Using process.exit() Function
  2. Using process.on() Function
  3. Using ctrl+C key

 

Using process.exit()

 

In Node.js, the process.exit() method is used to terminate the program explicitly with out the permission of the program. It has a single parameter: a status code. A status code status of code 0 indicates it’s a successful; error. While almost process.exit() all is other useful for quitting an application right away, it should be used carefully. This method immediately terminates the application, even if been there finished. are Because some of the operations its that abrupt haven’t nature, it is important to ensure that no crucial tasks are left undone before calling it.

 

Example: Basic use of process.exit()

console.log("Starting the application...");

setTimeout(() => {
  console.log("Exiting the application...");
  process.exit(0); // Exit with success code
}, 2000);

console.log("This message is displayed before exit.");

Output:

Starting the application...
This message is displayed before exit.
Exiting the application...

In this example, the program logs a 2 messages  synchronously:”Starting the application…” and “This message is displayed before exit.” After a 2-second delay, the setTimeout() callbacks “Exiting the application…” and then terminates the program using process.exit(0) statement

 

Using process.on()

 

Example: Listening for the exit Event

process.on("exit", (code) => {
  console.log(`The process is exiting with code: ${code}`);
});

console.log("Application is running...");
process.exit(0); // Triggers the exit event

Output:

Application is running...
The process is exiting with code: 0

In this example, process.on(“exit”) is used to perform tasks just before the application ends and when the process.exit(0) is called It triggers exit

 

Using ctrl + C Key

 

When running a code in the Node.js we can directly terminate the code by just pressing ctrl + c key in console

Example: Here is the example code

console.log('The program is running. Press Ctrl + C to stop.');

setInterval(() => {
  console.log('Still running...');
}, 1000);

Output:

The program is running. Press Ctrl + C to stop.
Still running...
Still running...
Still running...
Still running...
...

This program will keep Printing “Still running…” until we press “ctrl + C” key explicitly to stop

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top