Do you need to know how to exit or terminate a Node.js program?

You can do it with either the process.exit() function or by setting the process.exitCode variable and letting the program exit gracefully on its own.

In this article, we'll go over each of those methods and also provide you with some code samples you can use on your own.

Let's get started!

Table of Contents

Method 1 — process.exit()

The first method is the process.exit() method. This function tells Node.js to terminate the process synchronously with a given exit status code. Node.js will wait until all of the "exit" event listeners have been called before terminating.

To exit a program with a "failure" code, here's what the code would look like:


By calling this function, Node.js will force the current process that's running to exit as soon as possible. If there are any asynchronous operations taking place, they will be terminated immediately.

Most of the time, it isn't necessary to call this function explicitly in your code because the Node.js process will handle its exit on its own if there isn't any additional pending work on its event loop.

The process.exitCode is a more suitable solution in most use-cases. We'll cover that method in the next section.

You can check out the full list of process.exit() codes at this link.

Method 2 — process.exitCode

The process.exitCode is an integer that represents the code passed to the process.exit() function or when the process exits gracefully on its own.

In the previous example, we introduced you to the process.exit() function.

Here is an improper use of that method:

      if (someCondition === false) {

This is improper because the process.stdout method in Node.js is sometimes asynchronous and may take multiple ticks of the event loop to complete. In that case, calling process.exit() could force Node.js to exit before those event loops and subsequent stdout writes can be finished.

Instead, you should set the process.exitCode value and let the Node.js program exit gracefully on its own without scheduling any additional work for the future:

      if (someCondition === false) {
        process.exitCode = 1

This method is safer and will result in less issues in your Node.js code.


In this article, you learned two methods to exit or terminate a Node.js program: call the process.exit() function or set the process.exitCode variable and let the program exit on its own gracefully.

Thanks for reading and happy coding!