← 中文资源

简体中文版本

process.exitCode 报告 CLI 执行结果

用 process.exitCode 代替 process.exit 设定退出码:事件循环排空后状态才被读取,缓冲输出不会截断,多项检查聚合成单一退出状态供脚本判断。

阅读英文原文

实现说明

process.exitCode 报告 CLI 执行结果的核心是函数 runChecks。 这里叠了两层循环:for (const p of paths) 负责挑选,for (const problem of problems) console.error(problem); 负责处理。node:fs 提供 existsSync、statSync——内建表面,不涉及任何包。

使用要点

  • 无需安装:node:fs 随 Node.js 本体提供。
  • 演示输出是带标签的(problems found:、exit status will be),每个操作都会留下自己的一行标注。

常见问题

它从项目之外导入了什么?

只有 node:fs,而它是 Node.js 内建的——随运行时提供。

签名一览:function runChecks(paths)

核心语句

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;

代码示例

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);