LEARNNode CLI Automation

Exiting A Node.js Process

The Node.js provides you a global process object that you can use to control your Node.js processes. If you want to exit some process, you can easily do that with it. Let's discuss what are some of the ways of exiting a Node process.

process.exit Method

You can exit from any process with process.exit() method. It also takes an exit code. If you don't provide it, the process.exit() will either use the success code 0 or the value of process.exitCode if it is set.

You can provide the exit codes like this:

process.exit(0);

If the exit code is set to 1, it means that an uncalled fatal exception happened.

This is generally not the recommended way of exiting from a process. Instead of setting the exit code to 1 in the process.exit() method, you can do the following:

// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
printUsageToStdout();
process.exitCode = 1;
}

In the above piece of code, you are just setting the value of process.exitCode. And since you are not providing any exit code as a parameter to the process.exit() function, this exit code will be used.

Wrapping Up

These are the two ways you can use to properly exit from any Node.js process. For more detailed information, go ahead and read the documentation of process.exit() method.

Posted by Saad (It's a work in progress: Needs copy editing review by Awais.)