← Back to Node.js, page 4

nodejs-0078 · Medium mid

What is the difference between process.exit(), process.exitCode, the 'beforeExit' event and the 'exit' event?

process.exitCode sets the code the process will use when it ends naturally. process.exit(code) ends it at once. 'beforeExit' fires when the event loop becomes empty and lets you schedule more work, but not on process.exit() or an uncaught exception. 'exit' fires always at the end and can only run synchronous code.

Full answer

Exit codes tell the caller what happened: 0 means success, any other number means failure. By convention 1 is a general error, 2 is misuse of a command, and 128 + n means "killed by signal n" (143 for SIGTERM, 130 for SIGINT). Node itself uses 1 for uncaught exceptions and unhandled rejections.

Ways to end a process:

  • Natural end: the event loop has no more work. The exit code is process.exitCode (or 0).
  • process.exitCode = 2: only sets the code. Pending work continues, and output is flushed. Preferred.
  • process.exit(2): stops immediately. Pending timers, I/O and unflushed writes are dropped. Use it only after cleanup, or in a deliberate abort.
  • process.abort(): crashes with a core dump, for diagnostics.
  • An uncaught exception or unhandled rejection: code 1, unless handlers say otherwise.

Events:

  • 'beforeExit' (code): emitted when the loop empties. A handler can start new asynchronous work, and the process continues. It is not emitted for process.exit() or fatal errors. Beware of infinite loops: a handler that always schedules work never lets the process end.
  • 'exit' (code): emitted when the process is about to end, for every reason except a hard crash or SIGKILL. Only synchronous code is safe. Timers and I/O started here never run, so do not count on promise callbacks either.
  • 'uncaughtException' and 'unhandledRejection': see the error handling questions.

Uses: a command-line tool sets exitCode = 1 when validation fails, so CI stops. A 'exit' handler can write a final synchronous log line or remove a lock file.

javascript
const { spawnSync } = require('node:child_process');

function run(label, code) {
  const result = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
  console.log(label.padEnd(34), '| code:', result.status, '| stdout:', JSON.stringify(result.stdout.trim()));
}

run('natural end', `console.log('done')`);

run('exitCode set, work continues', `
process.exitCode = 4;
setTimeout(() => console.log('timer still ran'), 20);
`);

run('process.exit drops pending work', `
setTimeout(() => console.log('this timer never runs'), 20);
process.exit(5);
`);

run('exit handler runs sync code only', `
process.on('exit', (code) => {
  console.log('exit handler, code', code);
  setTimeout(() => console.log('never printed'), 0); // timers and I/O started here never run
});
process.exitCode = 6;
`);

run('beforeExit can schedule more work', `
let rounds = 0;
process.on('beforeExit', () => {
  if (rounds++ < 2) {
    console.log('beforeExit round', rounds);
    setTimeout(() => console.log('  work added in round', rounds), 5);
  }
});
`);

run('beforeExit is skipped by process.exit', `
process.on('beforeExit', () => console.log('never printed'));
process.exit(0);
`);

Each case runs in its own child process, so the exit code can be read by the parent. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): natural end | code: 0 | stdout: "done" exitCode set, work continues | code: 4 | stdout: "timer still ran" process.exit drops pending work | code: 5 | stdout: "" exit handler runs sync code only | code: 6 | stdout: "exit handler, code 6" beforeExit can schedule more work | code: 0 | stdout: "beforeExit round 1\n work added in round 1\nbeforeExit round 2\n work added in round 2" beforeExit is skipped by process.exit | code: 0 | stdout: ""

Key points

  • exitCode sets the code. exit() stops immediately.
  • beforeExit can schedule more work. exit cannot.
  • 128 + signal number is the convention for signals.
  • Prefer exitCode and a natural end.

Common mistakes

  • Calling process.exit() right after logging and losing output.
  • Doing asynchronous clean-up in an 'exit' handler.
  • Using exit code 0 when a CLI validation failed.
  • Creating an endless loop with beforeExit.

Follow-ups

  • What exit code does a process killed by SIGTERM report?
  • How would you make a CLI return different codes for different errors?
  • How does a shell script test the exit code?

Tips

  • Say 'exitCode and let the loop end' as the default advice.
  • Remember that exit handlers are synchronous.
  • Know the 128 + n convention.