Node.js

Report CLI failure with process.exitCode

Set process.exitCode when a command should report failure after finishing normal cleanup. This lets the event loop and pending output complete instead of forcing immediate termination.

Worked example

Node.js example · save as example.mjs and run node example.mjs

async function main() {
  return "Finished work";
}
try {
  console.log(await main());
} catch (error) {
  console.error(error.message);
  process.exitCode = 1;
}

How it works

The success path ends naturally with the normal zero status. If main rejects, the catch block reports a concise message and assigns a nonzero status. This structure works well with finally blocks that release resources before the process becomes idle.

Limits and mistakes

Setting exitCode does not stop timers, open servers, or background work. Close those resources deliberately. Conversely, calling process.exit too early can cut off asynchronous writes or prevent cleanup code from running.

Check the result

Expect Finished work and a successful status. Replace main with a deliberate throw in a separate fixture and confirm the shell receives status 1 after the diagnostic is printed.

Sources

Reference documentation for the behavior used in this guide: