process.on()
Registers a listener for process-level events and signals.
Syntax
process.on(event, listener) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
event | string | Yes | The event name, e.g. `'exit'`, `'SIGINT'`, `'SIGTERM'`, `'uncaughtException'`, `'unhandledRejection'`, `'beforeExit'`. |
listener | function | Yes | The handler invoked when the event fires. |
Returns
process — The process object, for chaining.
Examples
process.on('SIGINT', () => {
console.log('shutting down');
process.exit(0);
});
Output
shutting down
process.on('unhandledRejection', (reason) => {
console.error('unhandled rejection:', reason);
process.exitCode = 1;
});
Output
unhandled rejection: Error: boom
Notes
Use `SIGINT`/`SIGTERM` for graceful shutdown (close servers and DB
pools). Inside `'exit'` only synchronous work runs. Treat
`'uncaughtException'` as a last resort for logging then exiting, not
for resuming normal operation.