DhiWise
Published in

DhiWise

The Execution of Node.js Process

There are several things that can cause a Node.js process to terminate. Some of them are preventable, like when an error is thrown, while others cannot be prevented, like running out of memory. The process global is an Event Emitter instance and, when a graceful exit is performed, will emit an exit event. Application code can then listen to this event to perform some last minute synchronous cleanup work.

Photo by Max Chen on Unsplash

Following are ways that a process termination can be intentionally triggered:

Process Exit

The process.exit(code) approach to process termination is the most straightforward tool at your disposal. It’s very useful when building scripts when you know that your process has reached the end of its lifetime. The code value is optional and defaults to 0 and can be set to a number as high as 255.

A 0 represents a successful process run, while any non-zero number means a failure happened. These values are used by many different external tools. For example, when a test suite runs, a non-zero value means the tests have failed.

When process.exit() is called directly there is no implicit text written to the console. If you have written code that calls this method in representation of an error, then your code should print an error for the user to help them out.For example, run the following code:

$ node -e “process.exit(42)”

$ echo $?

In this case no message was printed by the one-line Node.js application, though the shell did print the exit status. A user encountering such a process exit is not going to understand what’s happening. On the other hand, consider this code that might run when a program is configured incorrectly:

function checkConfiguration(config) {

if (!config.host) {

console.error(“Configuration is missing ‘host’ parameter!”);

process.exit(1);

}}

In this situation there is no ambiguity for the user. They run the app, an error is printed to the console, and they’re able to rectify the situation.

It’s worth noting that the process.exit() method is extremely powerful. While it has its purposes in application code it should really never make its way into a reusable library.

If you like what you read here, clap and share.

Stay tuned for the next article which contains Exception, Rejection, and Emitted Errors.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Zaiynab Mansuri

Zaiynab Mansuri

Tech Enthusiast | JavaScript Coder | Node.Js