How to exit from node JS program Programmatically

By

How to exit from node JS program Programmatically

By bangarsanju12

This is one of the most common scenario where you want to close your program. if you want to terminate your program while  while the application is running there are a variety of ways we do it . Make sure you know how to write a simple nodejs program .

 one of the way is by using Control + c ,  but what we are  you are getting here is we want to close our program programmatically. In order to achieve this we are going to use the process module present in NodeJS. Lets see How and Is it a good way of doing it ?

Also Read :-

  1. Best Ways to Check If an Object is Empty In JavaScript
  2.  Configure Node Js for Production and Development
  3. How to Master Cron Jobs Nodejs
  4. How to Read Files in Nodejs with examples

 What is a Process module?

Using process model we can get all the information of your current node.js environment or process. It is a global object accessible across your node JS program for NodeJS process .

Let’s have a look how you can use the node.js process module in our code

Process program is always accessible across node JS module without using require(). Although if you want to try it using require you can do it like below .

const process = require('process');

How to exit from a node JS program

 So using a process core module we can exit from our NodeJS program as shown below

process.exit()

When above line is executed in your node.js program your program will terminate explicitly , any process anything running on background . Any task that is running will be terminated abruptly.

You can also use something like this below

process.exit(1)

Now there is a Slight Difference ,

By default the exit code is 0, which means success. Different exit codes have different meaning, which you might want to use in your own system to have the program communicate to other programs. Have a look at all exit codes here .

Now what does 1 in the above line of code signify, so one is basically the exit code that you pass to your OS, by default the Exit code is zero which means success . There are different exit codes which has different meanings and you can add your exit code as per your requirement.

 But this is not the correct way to exit from your node JS program programmatically . let’s have a look .

Simple Exit using Callback In Nodejs

We are going to wait for our script to execute and then exit from our code . So one the program completes it exits from code automatically like shown below.


//filename test-nodejstut.js

process.on('exit', function(code) {
    return console.log(`Exiting Nodejs With Exit Code : ${code}`);
});

Note :- You do not need to import process .

Now what happens if we have a set of code that runs for indefinite time before our process.on callback?



//filename test-nodejstut.js

setInterval((function() {
    return console.log('Nodejs Tutorials.net');
}), 1000);

process.on('exit', function(code) {
    return console.log(`Exiting Nodejs With Exit Code : ${code}`);
});

So what should be the output ? Have a look at the output .

exit nodejs program programatically

So what happens above ? The code above wont exit and move inside the process.exit() callback , unless the above block of code finish execution .

Correct Way Of Exiting From Nodejs Code

Now , lets say you have a simple NodeJS server running as shown below and you have used process.exit(1) in your code .

const express = require('express')

const app = express()

app.get('/', (req, res) => {
  res.send('Hi Nodejstuts!')
})

const server = app.listen(3000, () => console.log('Server Listening In Nodejstuts'))

So what happens ? Your server immediately turned off and incoming socket connections will be in hung state till it reaches your defined timeout . Now , this is unnecessary use of resources and bad experience to your users in case of huge load .

How can we Correct it ?? So the Answer is OS Signal Events .

OS Signal Events :-

A better way to kill the application is to send an event to the node JS process and gracefully shutdown the server . A better way of doing this would be using OS Signal Events .

With OS signal events your node.js process can catch any OS based events , That is sent by your operating system.  Few of the common signals are SIGTERM and SIGINT.

SIGINT  is used when a node JS process is interrupted usually by pressing Control + c.

 Have a look how we can use a signal events to stop the  Express server explained in the example above.

We are using process.kill(process.pid, 'SIGTERM') in our Nodejs code to shutdown the server programmatically and implementing the SIGINT and SIGTERM callbacks.

const express = require('express')

const app = express()

app.get('/', (req, res) => {
  res.send('Hi Nodejstuts!')
  process.kill(process.pid, 'SIGTERM')

})

const server = app.listen(3000, () => console.log('Server Listening In Nodejstuts'))


process.on('SIGTERM', signal => {
  console.log(`Process ${process.pid} received a SIGTERM signal`)
  process.exit(0)
})

process.on('SIGINT', signal => {
  console.log(`Process ${process.pid} has been interrupted`)
  process.exit(0)
})

So now these two events are considered to be successful termination and we are returning process that exit 0 in the parameter.  We are putting 0 because it is something that it is expected hence we are putting it is zero and considering it as graceful shutdown.

Conclusion :-

process.exit() will terminate a process immediately and you cannot do anything based on any particular event that you want to do before your application is terminated.\

 using OS Signal events  You can control your server termination and you can do any kind of processing that you want.  It provides you more control on your termination logic.

Please let us know if any questions !

Happy Coding !!

Leave a Comment