Correct exit codes and signal handling are how your program cooperates with shells, CI and container platforms.
process is a global object describing the running Node process. The parts you will use:
process.argv— command-line arguments;[0]is the node binary,[1]the script, the rest are yours.process.env— environment variables (next lesson).process.cwd()— current working directory;process.chdir()changes it.process.stdout,process.stderr,process.stdin— the standard streams.console.logwrites to stdout,console.errorto stderr. Send diagnostics to stderr so stdout stays clean for piping.process.pid,process.platform,process.version,process.memoryUsage(),process.uptime().
Exit codes tell the caller whether you succeeded: 0 means success, anything else failure. Node exits with 0 when the event loop empties, and with 1 on an uncaught exception or unhandled rejection. To report failure yourself, prefer setting process.exitCode = 1 and letting the program finish naturally. process.exit(code) stops immediately: pending writes to stdout, open file handles and in-flight requests are cut off, which can truncate output when piped.
Signals let other programs ask you to stop. Ctrl+C sends SIGINT; Docker, Kubernetes and systemd send SIGTERM. Without handlers Node exits right away. Listen with process.on("SIGTERM", ...) to finish work and close servers first — the basis of graceful shutdown.
The "exit" event fires as the process ends, but only synchronous code runs inside it. For async cleanup, use "beforeExit" (fires when the loop empties naturally) or handle the signal.
Example
// sum.js — usage: node sum.js 3 4 5
const nums = process.argv.slice(2).map(Number);
if (nums.length === 0 || nums.some(Number.isNaN)) {
console.error("usage: node sum.js <number...>"); // diagnostics -> stderr
process.exitCode = 2; // fail, but let output flush
} else {
console.log(nums.reduce((a, b) => a + b, 0)); // result -> stdout
}
process.on("SIGINT", () => {
console.error("\ninterrupted, cleaning up");
process.exitCode = 130; // conventional for Ctrl+C
});
process.on("exit", (code) => console.error(`exiting with ${code}`));
// $ node sum.js 3 4 5 ; echo $? -> 12, exiting with 0, 0Remember
process.argv.slice(2)are your arguments- Prefer
process.exitCode = noverprocess.exit(n) - Results to stdout, diagnostics to stderr
- Handle SIGINT/SIGTERM to shut down cleanly
Watch out for
- Calling
process.exit()right after writing output, truncating it when piped.