Typorithm · medium

Signals & Exit

node-signals-exitnodejssignalsgraceful-shutdownexit
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Signals & Exit

0%

CLI & Process

Listen for SIGINT (Ctrl-C) and SIGTERM (kill/orchestrators) to shut down gracefully — close servers and the database, then call process.exit(0) for success or a non-zero code for failure. The "exit" event is for final synchronous cleanup only; never start async work there.

process.on("SIGINT", ...) handles Ctrl-C and process.on("SIGTERM", ...) handles the signal orchestrators send; both give you a chance to shut down gracefully — close HTTP servers and database connections so in-flight requests complete instead of being severed.

process.exit(code) ends the process immediately with an exit code: 0 means success and any non-zero value means failure, which is how shells and CI pipelines decide whether your program succeeded.

process.on("exit", ...) fires as the process is already leaving, so only synchronous cleanup runs — any async work (awaits, timers, I/O) inside an exit handler is silently dropped, so do that draining in the signal handler instead.

01

SIGINT = Ctrl-C; SIGTERM = kill / orchestrators.

02

exit(0) = success; non-zero = failure.

03

The "exit" event runs only synchronous cleanup.

process.on("SIGINT", shutdown)   // Ctrl-C
process.on("SIGTERM", shutdown)  // kill / orchestrators
async function shutdown() {
  await server.close()
  await db.close()
  process.exit(0)   // 0 = success, non-zero = failure
}
process.on("exit", (code) => log(`exiting ${code}`))

Read the implementation

Connect each part of the code to the concept before you type.

1. Handle Ctrl-C

SIGINT is sent when the user presses Ctrl-C; handling it lets you clean up instead of dying abruptly.

process.on("SIGINT", shutdown)   // Ctrl-C

2. Handle SIGTERM

SIGTERM is what kill and orchestrators like Kubernetes send to ask a process to stop gracefully.

process.on("SIGTERM", shutdown)  // kill / orchestrators

3. Drain resources

Graceful shutdown means closing the server and database before exiting so in-flight work finishes.

await server.close()

4. Exit code

process.exit(0) signals success; any non-zero code signals failure to the calling shell.

process.exit(0)   // 0 = success, non-zero = failure

5. exit event

The "exit" event fires as the process is leaving; only synchronous work runs here.

process.on("exit", (code) => log(`exiting ${code}`))

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Signals & Exit: Lesson & Practice · Typorithm | ApplyDjinn