process.exitCode Reports CLI Outcome

Set process.exitCode instead of calling process.exit so buffered output drains first, and summarize batch checks into one exit status for shell scripts.

JavascriptCli Tooling

Code

javascriptsnippet
22 lines
import { existsSync, statSync } from 'node:fs';

// Collect every problem instead of stopping at the first one.
function runChecks(paths) {
  const problems = [];
  for (const p of paths) {
    if (!existsSync(p)) {
      problems.push('missing: ' + p);
      continue;
    }
    if (statSync(p).size === 0) problems.push('empty: ' + p);
  }
  return problems;
}

const problems = runChecks(['./exists.txt', './missing.txt', './empty.txt']);
for (const problem of problems) console.error(problem);
console.log('problems found:', problems.length);

// 0 stays success; anything else becomes the exit status once the loop drains.
process.exitCode = problems.length === 0 ? 0 : 1;
console.log('exit status will be', process.exitCode);

Inside the snippet

process.exitCode Reports CLI Outcome is built around the function runChecks.

The nesting pairs for (const p of paths) with for (const problem of problems) console.error(problem); — the inner runs once per outer step. existsSync, statSync come from node:fs — Node.js core modules the runtime ships with.

What to watch for

  • The only import, node:fs, is part of the Node.js standard library.

Using it

Entry signature: function runChecks(paths)

The demo output is labeled (problems found:, exit status will be), so every printed line maps back to its originating operation.

Key statements

const problems = runChecks(['./exists.txt', './missing.txt', './empty.txt']);
if (statSync(p).size === 0) problems.push('empty: ' + p);
process.exitCode = problems.length === 0 ? 0 : 1;

Interactive Tools for This Topic

FAQ

What does this import from outside the project?
Only `node:fs`, and that is a Node.js built-in — it comes with the runtime.