How to exit in Node.js?
Exiting a Node.js process can be done in a few different ways, depending on your context. Below are the most common approaches:
1. Using process.exit(code)
Node.js provides the built-in process.exit()
method, which immediately ends the process with the provided exit code:
console.log('Exiting...'); process.exit(0); // 0 generally indicates a successful exit
process.exit(0)
: Indicates a normal, successful termination.process.exit(1)
: Signals an error or abnormal termination.
Note: process.exit()
immediately stops the Node.js event loop, so any asynchronous callbacks or operations still pending will not complete. If you have ongoing tasks like database writes or open file handles, ensure they finish first—or handle them gracefully—before calling process.exit()
.
2. Using Ctrl + C in the Terminal
When running a Node.js script or the Node REPL (interactive shell) in a terminal, you can terminate the process by pressing Ctrl + C. This sends a SIGINT
signal, which usually kills the process unless you have a custom signal handler that intercepts it.
3. Exiting the Node REPL Manually
If you’re working in the Node REPL (i.e., after typing node
with no script name):
- Type
.exit
and press Enter. - Or press Ctrl + C twice.
Either action will end the REPL session.
4. Graceful Shutdown in Larger Applications
For longer-running services (e.g., servers), it’s often better to gracefully close resources rather than abruptly calling process.exit()
. For example:
function gracefulShutdown(server) { console.log('Closing server...'); server.close(() => { console.log('Server closed. Exiting now.'); process.exit(0); }); }
This ensures all open connections and ongoing requests finish before exiting. A similar approach applies for database connections or other resources that need clean-up to avoid data loss or corruption.
Recommended Resource
Summary
process.exit(code)
: Immediately terminates the process with a given exit code.- Ctrl + C: Kills a Node process or REPL in the terminal.
.exit
: Exits the Node REPL.- Graceful Shutdown: Close resources like HTTP servers, database connections, or file streams before exiting to avoid data issues or incomplete operations.
Choose the method that fits your scenario:
- Command-line usage: Ctrl + C or
.exit
. - From code:
process.exit()
(with caution, ensuring critical clean-up is done). - Robust apps: Graceful shutdown patterns to release resources properly.