process.exit
- Node.js course
- Intermediate
- Lesson 61/116
- 5 min
Learn exit codes with process.exit.
What is process.exit?
process.exit() terminates the running process immediately. You give it an exit code: 0 means success, any non-zero value means an error. This code is read by the shell that called the script.
For example, when an error occurs you write process.exit(1) to end the process with an error code. But be careful: process.exit exits right away without waiting for the event loop; pending logs or open files may be lost. That is why it is usually safer to set process.exitCode and let the process finish naturally. Still, in emergencies process.exit is useful.
Safe exit with exitCode
The process.exitCode property sets the exit code the process will return at the end. Unlike process.exit, it does not kill the process right away; it lets the event loop drain and open resources close.
For example, if you write process.exitCode = 0;, the program returns this code when it finishes naturally. On an error you set process.exitCode = 1; and give the process a chance to end on its own. This matters especially when there are database connections or open files, because a sudden exit can cause data loss. The safe path is this method.
Practice Set exitCode and print it
Define const hasError = false;. With if (hasError) set process.exitCode to 1, otherwise to 0. Print process.exitCode with console.log.
Starter code
// Define hasError (false)
// Check with if, set exitCode
// Print with console.log
// write hereSample solution
const hasError = false;
if (hasError) {
process.exitCode = 1;
} else {
process.exitCode = 0;
}
console.log(process.exitCode);Expected output
0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each code to its meaning
| Term | Meaning |
|---|---|
0 |
Success |
1 |
General error |
process.exit |
Terminates the process |
exitCode |
Sets the exit code |
2 Which exit code means success?
process.exit(0)- 0 Correct answer
- 2
- -1
- 1
Explanation: 0 means success; any non-zero value means an error.
3 Exit with success
process.exit(____);
process.exit(0);
Explanation: process.exit(0) exits with success.