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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.