CLI 工具链
commander、chalk、nodemon、watch。
25 分钟
CLI 工具链
nodejs-advanced-essentials 的 nva-cli 讲 argv 与 stdin;本课从 运行时与 DX 角度补 commander、chalk、nodemon、watch——写可维护脚本、开发时快速迭代。
学习目标
- 用 commander 组织子命令与 option
- 用 chalk 区分 stderr 语义色(不滥用)
- 配置 nodemon 或 Node
--watch做热重载
commander 子命令
import { Command } from "commander";
import chalk from "chalk";
const program = new Command();
program
.name("nrt-demo")
.description("runtime essentials CLI demo")
.version("1.0.0");
program
.command("hash")
.argument("<text>", "input string")
.option("-a, --algo <name>", "hash algorithm", "sha256")
.action((text, opts) => {
console.log(JSON.stringify({ algo: opts.algo, text }));
});
program.parse();
复杂脚本拆 command 模块;与 nva-practice 的 import CLI 可共用同一套结构。
chalk 与输出约定
console.error(chalk.yellow("warn:"), "deprecated flag");
console.error(chalk.red("error:"), err.message);
console.log(chalk.green("done")); // stdout:可被管道消费
原则:结构化数据走 stdout 纯 JSON;人类可读进度走 stderr + chalk。CI 无 TTY 时 chalk 自动降级——勿依赖颜色解析输出。
nodemon 与 Node --watch
nodemon(路线图 nodemon):监听文件变更重启进程。
{
"watch": ["src"],
"ext": "js,json",
"exec": "node src/cli.js"
}
Node 20+ 内置:
node --watch src/cli.js
nrt-debug 调试时 nodemon 可能断掉 inspect 会话——可用 nodemon --inspect 或 VS Code compound launch。
环境变量与 dotenv
CLI 常读 process.env(node-runtime)。本地开发 dotenv/config 预加载;生产用 K8s Secret / 平台注入,不要把 .env 提交仓库。
与 npm scripts 集成
{
"scripts": {
"dev": "node --watch bin/cli.js",
"start": "node bin/cli.js"
},
"bin": { "nrt-demo": "./bin/cli.js" }
}