0
0
Node.jsframework~5 mins

process.exit and exit codes in Node.js

Choose your learning style9 modes available
Introduction

We use process.exit to stop a Node.js program immediately. Exit codes tell the system if the program ended well or had a problem.

When you want to stop your program early because of an error.
When a script finishes its job and you want to tell the system it ended successfully.
When you want to signal to other programs if your script failed or succeeded.
When you need to exit after checking some conditions in your code.
When writing command-line tools that need to return status to the operating system.
Syntax
Node.js
process.exit([code])

The code is a number. 0 means success, any other number means an error.

If you don't give a code, it defaults to 0.

Examples
Exit the program with code 0, meaning success.
Node.js
process.exit()
Exit the program with code 1, meaning there was an error.
Node.js
process.exit(1)
Exit with a custom error code 42 to indicate a specific problem.
Node.js
process.exit(42)
Sample Program

This program prints a start message. If you run it with --fail argument, it prints an error and exits with code 1. Otherwise, it prints a success message and exits with code 0.

Node.js
console.log('Start program');
if (process.argv.includes('--fail')) {
  console.error('Error: Something went wrong!');
  process.exit(1);
}
console.log('Program finished successfully');
process.exit(0);
OutputSuccess
Important Notes

Always use process.exit carefully because it stops the program immediately, skipping any remaining code.

Exit codes help other programs or scripts know if your program worked or failed.

Use 0 for success and positive numbers for errors. Negative numbers are not recommended.

Summary

process.exit stops a Node.js program immediately.

Exit codes tell if the program ended well (0) or had an error (non-zero).

Use exit codes to communicate status to the system or other programs.