How to Use process.exit in Node.js: Syntax and Examples
In Node.js, use
process.exit(code) to stop the program immediately with an optional exit code. A code of 0 means success, while any other number signals an error or specific status.Syntax
The process.exit() method stops the Node.js process immediately. It takes one optional argument:
code(number): The exit status code.0means success, any other number indicates an error or specific exit reason.
If no code is provided, it defaults to 0.
javascript
process.exit(code);
Example
This example shows how to exit a Node.js program with a success code 0 and an error code 1. The program prints a message before exiting.
javascript
console.log('Program started'); // Exit with success code 0 process.exit(0); // This line will not run console.log('This will not print');
Output
Program started
Common Pitfalls
Common mistakes when using process.exit() include:
- Calling
process.exit()before asynchronous tasks finish, causing data loss. - Not providing an exit code, which defaults to
0and may hide errors. - Expecting code after
process.exit()to run, but it never does.
Always ensure all important work is done before calling process.exit().
javascript
/* Wrong way: Exiting before async task finishes */ setTimeout(() => { console.log('Async task done'); }, 1000); process.exit(0); // Exits immediately, async task never runs /* Right way: Exit after async task */ setTimeout(() => { console.log('Async task done'); process.exit(0); // Exit after task }, 1000);
Output
Async task done
Quick Reference
Remember these tips when using process.exit():
- Exit code 0: Success
- Non-zero exit codes: Indicate errors or special conditions
- Use before exit: Finish all async work
- Code after exit: Will not run
Key Takeaways
Use process.exit(code) to stop Node.js immediately with an exit code.
Exit code 0 means success; non-zero codes signal errors or special states.
Never call process.exit() before finishing asynchronous tasks.
Code after process.exit() will not execute.
Always provide an exit code to clearly indicate program status.