DEV Community

Cover image for Lessons from opensource: What does process.exit do in Nodejs?
Ramu Narasinga
Ramu Narasinga

Posted on

Lessons from opensource: What does process.exit do in Nodejs?

As I was reading through the open source code at next.js’s create-next-app, I saw process.exit being used a lot of times. This made me read further about it and the following are my findings:

Image description
https://github.com/vercel/next.js/blob/canary/packages/create-next-app/create-app.ts#L79

What is process.exit()?

The process.exit() method instructs Node.js to terminate the process synchronously with an exit status of code. If code is omitted, exit uses either the 'success' code 0 or the value of process.exitCode if it has been set. Node.js will not terminate until all the 'exit' event listeners are called. — Source

Fun fact is that exit’s success code is 0 and failure code is 1, quite contradictory to what we conventionally use 1 aka true for success and 0 aka false for error.

// source: https://nodejs.org/api/process.html#processexitcode
import { exit } from 'node:process';

// This is an example of what *not* to do:
if (someConditionNotMet()) {
  printUsageToStdout();
  exit(1);
}
Enter fullscreen mode Exit fullscreen mode

The above code is not recommended because you could have some asynchronous operations in the function printUsageToStdout, these operations can vary from parsing a document, logging the operations info to writing to database. 

Because, exit(1) forces the process to exit before your function could finish those additional operations, this could mean if you were to call exit(1) in your catch block and you log some info to a file, this might be incomplete as your program ends.

Use exitCode instead:

// source: https://nodejs.org/api/process.html#processexitcode
import process from 'node:process';

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

When you use exitCode, you allow the process to exit naturally without any force shut.

If it is necessary to terminate the Node.js process due to an error condition, throwing an uncaught error and allowing the process to terminate accordingly is safer than calling process.exit(). — Source

Conclusion:

I used to write articles with the title Nextjs Codebase analysis, but after a couple of weeks, I realised it is more appealing and helpful to the developer community when I specifically write about the code used in open source that looks interesting. 

I did not know there is exitCode until I read the docs further. You can gain a lot of knowledge by reading open source code and see how the elitists are doing it. 

If you are looking to improve/learn frontend, checkout my website: https://tthroo.com/ where I write project based tutorials.

Top comments (0)