How To Exit from NodeJS Console From Script and Command

In this article of Nodejs Development Tutorials series, we are going to learn How to exit from Node command line on MAC, Windows, and Linux and How To Exit from Nodejs Script. So let’s start:

Article Contents

How to exit from Nodejs command line on MAC, Windows, and Linux using CTRL+C

Let’s consider the situation where Nodejs is connected to the Your Database everytime you run your app and after finishing your process, you need to manually press CTRL+C and if you want to exit the Nodejs console after finishing the process you can use below code snippet at the end of your code, it will automatically exit the Nodejs for you.

  • you can use CTRL+C twice as show in below gif to exit from nodejs console.
  • nodejs console
  • You can also use process.exit() or .exit command to exit from nodejs console
    //exit nodejs using process.exit()
    $ node
    > 10+21
    31
    > 50-10
    40
    > process.exit()
    $ 
    
    
    //exit nodejs using .exit  command
    $ node
    > 11+22
    33
    > 60-30
    30
    > .exit
    $ 
    
    //you can use any method from CTRL+C twice or process.exit() or .exit
    

     

  • process.exit([code]) can be used to exit with success or error code, which we will see below.

 

How to exit from NodeJS from Script on MAC, Windows, and Linux

Normally Node.JS Scripts stops at the end of the code or when there are no events to handle and what if you want to exit in the middle of the script, if any error occurs or warning, then you should follow the below code to get your job done.

Node.JS’s Process Module has a method called Exit.

The Method we are going to use is  process.exit([code])

  • In the above code snippet process.exit([code]), the code is passed as the parameter, which is integer value and by default, it’s “0”. which indicated exited with success code zero.
    process.exit([0])
  • To exit with failure code you need to specify process.exit([1]), which means nodejs process exited with failure code 1.
    process.exit([1])
  • Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations.
    // How to use process.exit properly
    if (ConditionNotMet()) {
      //do something
     //notify and then
      process.exitCode = 1;
    }

If this article helped you, then please share, comment and subscribe to our awesome articles newsletter and also check out:

See also  Introduction MEAN Stack Development [For Developers & Beginners]

Leave a Comment