🚀 安装与初始化 >>>
声明变量
// CommonJS
const { program } = require('commander');
// 或者创建本地实例
const { Command } = require('commander');
const program = new Command();
// TypeScript
import { Command } from 'commander';
const program = new Command();
⚡ 快速开始 >>>
const { program } = require('commander');
program
.option('--first')
.option('-s, --separator ');
program.parse();
const options = program.opts();
const limit = options.first ? 1 : undefined;
console.log(program.args[0].split(options.separator, limit));
// 入口文件执行, 类似于python的 __name__ === '__main__'
const __filename = fileURLToPath(import.meta.url);
const entryFile = process.argv[1];
if (path.resolve(__filename) === path.resolve(entryFile)) {
// 定义
}
运行: node split.js -s / --first a/b/c
⚙️ 基础选项 >>>
.option(flags, description, [default]):定义选项
program
.option('-d, --debug', 'output extra debugging')
.option('-s, --small', 'small pizza size')
.option('-p, --pizza-type ', 'flavour of pizza');
const options = program.opts();
if (options.debug) console.log(options);
flags 可以包含短标志(-d)和长名称(--debug)。
⚙️ 选项默认值 >>>
program.option(
'-c, --cheese ',
'add the specified type of cheese',
'blue' // 默认值
);
🔧 高级选项类型 >>>
取反布尔值 (Negatable)
program.option('--no-sauce', 'Remove sauce');
// 使用 --no-sauce 时,sauce 值为 false
必填选项 (Required)
program.requiredOption('-c, --cheese ', 'pizza must have cheese');
// 若未提供,程序会自动报错并退出
变长参数 (Variadic)
program.option('-n, --number ', 'specify numbers');
// 解析结果为数组: { number: ['1', '2', '3'] }
🛠️ 选项配置与处理 >>>
版本选项
program.version('0.0.1', '-v, --vers', 'output current version');
自定义处理函数
function myParseInt(value, dummyPrevious) {
return parseInt(value);
}
program.option('-i, --integer ', 'int arg', myParseInt);
更多配置 (Option 对象)
new Option('-t, --timeout ', 'timeout in seconds')
.default(60, 'one minute')
.choices(['small', 'medium', 'large'])
.env('PORT') // 从环境变量读取
.conflicts('port') // 冲突检测
.implies({ drink: 'small' }) // 隐含选项
📦 定义命令 >>>
.command('name '):定义命令
.action(fn):命令处理函数
program
.command('clone [destination]')
.description('clone a repository')
.action((source, destination) => {
console.log('cloning ' + source);
});
参数语法
<required>:必填参数
[optional]:可选参数
variadic...:变长参数(只能是最后一个)
📂 独立可执行子命令 >>>
当 command() 带有描述参数时,Commander 会将其视为独立可执行文件。
program
.command('install [package-names...]', 'install packages')
.command('search [query]', 'search with optional query');
会自动寻找 pm-install, pm-search 等文件执行。
📝 命令参数详解 >>>
使用 .argument()
program
.version('0.1.0')
.argument('', 'user to login')
.argument('[password]', 'password', 'default')
.action((username, password) => {
// ...
});
自定义参数处理
program
.command('add')
.argument('', 'integer', myParseInt)
.action((first) => { /* ... */ });
🪝 生命周期钩子 >>>
preAction:Action处理前
postAction:Action处理后
program
.option('-t, --trace', 'display trace')
.hook('preAction', (thisCommand, actionCommand) => {
if (thisCommand.opts().trace) {
console.log('About to call action handler');
}
});
❓ 帮助系统 >>>
自定义帮助内容
program.addHelpText('after', `
Example call:
$ custom-help --help`);
错误后显示帮助
program.showHelpAfterError('(add --help for additional information)');
代码中显示帮助
program.help(): 显示并退出
program.outputHelp(): 仅显示
⚙️ 程序配置 >>>
program
.name("my-command")
.usage("[global options] command")
.description("CLI description")
.summary("short summary"); // 用于子命令列表
自定义帮助选项/命令
program.helpOption('-e, --HELP', 'read more info');
program.helpCommand('assist [command]', 'show assistance');
▶️ 解析与执行 >>>
同步解析
program.parse(); // 默认解析 process.argv
program.parse(process.argv); // 显式传递
program.parse(['-f', 'filename'], { from: 'user' });
异步解析
await program.parseAsync(process.argv);
如果有 async action handler,必须使用 parseAsync。
⚠️ 错误与输出控制 >>>
自定义错误
program.error('Password must be longer than four characters');
覆盖退出行为
program.exitOverride(); // 抛出错误而不是直接退出
try {
program.parse(process.argv);
} catch (err) {
// handle error
}
自定义输出
program.configureOutput({
writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
outputError: (str, write) => write(`\x1b[31m${str}\x1b[0m`)
});