How to exit in Node.js

Better Stack Team
Updated on March 11, 2024

Exiting a Node.js application is simple and can be done using the process.exit() method. This method exits from the current Node.js process and takes an exit code, which is an integer. The exit code can be either 0 or 1. 0 means end the process without any kind of failure and 1 means end the process with some failure.

Here’s how you can use the process.exit() method:

 
if (someConditionNotMet()) {
  console.log('Usage: node <filename>');
  process.exit(1);
}

In the above example, if someConditionNotMet() returns true, the message Usage: node <filename> is printed to the console and the process exits with an exit code of 1.

It’s important to note that 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 to process.stdout and process.stderr In most situations, it is not actually necessary to call process.exit() explicitly. The Node.js process will exit on its own if there is no additional work pending in the event loop.

Here are some other ways to exit a Node.js application:

  1. Throwing an Error: You can throw an error to exit a Node.js application. This method is useful when you want to exit the application with a specific error message.
 
throw new Error('Something went wrong');
  1. Using the process.kill() Method: You can use the process.kill() method to terminate a Node.js process. This method sends a signal to the process to terminate it. The signal can be either SIGTERM or SIGKILL.
 
process.kill(process.pid, 'SIGTERM');
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github