一、问题现象说明:
1. 问题描述:
commander 的 option 事件不执行;
2. 问题现象:
安装 commander 的 11.1.0版本
npm i commander@11.1.0
相关测试代码
const commander = require("commander");
const program = new commander.Command();
program
.name("test-cli")
.usage("<command> [options]")
.version("1.0.0")
.option("-tp, --target-path <target-path>", "Whether to specify a local debug file path?", "");
program
.command("init [projectName]")
.option("-f, --force", "Whether to force to init the program? ")
.action(function (projectName, cmdObj, program) {
//console.log("init 的回调");
})
program.on("option: target-path", function(){
console.log("target path test");
});
program.parse(process.argv);
当执行脚手架时:
test-cli init --target-path /xxx
target-path 事件下面的 targe path test 测试文字不打印,也就是这个事件没有执行。
二、问题原因:
program.on("option: target-path", function(){
console.log("target path test");
});
option:后面不能加空格,加了空格,这个命令就监听不到了。
三、解决方案
去掉 option冒号后面的空格就可以了,如下所示:
program.on("option:target-path", function(){
console.log("target path test");
});
四、复现上述问题的完整步骤
1. 创建项目test-cli
mkdir test-cli-commander
2. 初始化项目test-cli-commander
cd test-cli-commander
npm init
3. 安装 commander 依赖包版本11.1.0
npm i --save-dev commander@11.1.0
4. 添加入口文件 bin/index.js 并添加如下代码
#! /usr/bin/env node
const commander = require("commander");
const program = new commander.Command();
program
.name("test-cli")
.usage("<command> [options]")
.version("1.0.0")
.option("-tp, --target-path <target-path>", "Whether to specify a local debug file path?", "");
program
.command("init [projectName]")
.option("-f, --force", "Whether to force to init the program? ")
.action(function (projectName, cmdObj, program) {
//console.log("init 的回调");
})
program.on("option: target-path", function(){
console.log("target path test");
});
program.parse(process.argv);
5. 在package.json 中添加 脚手架命令 test-cli 的配置;
{
"name": "test-cli-commander",
"version": "1.0.0",
"description": "",
"main": "index.js",
"bin": {
"test-cli": "bin/index.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"commander": "^11.1.0"
}
}
6. 执行npm link本地调试脚手架文件;
npm link
7. 执行脚手架命令 test-cli 查看现象;
上述执行现象可以看到 没有返回 target-path 的option事件中的打印文字 “target path test”;
8. 问题解决之后的完整代码如下:
#! /usr/bin/env node
const commander = require("commander");
const program = new commander.Command();
program
.name("test-cli")
.usage("<command> [options]")
.version("1.0.0")
.option("-tp, --target-path <target-path>", "Whether to specify a local debug file path?", "");
program
.command("init [projectName]")
.option("-f, --force", "Whether to force to init the program? ")
.action(function (projectName, cmdObj, program) {
// console.log("init 的回调");
})
program.on("option:target-path", function(){
console.log("target path test");
});
program.parse(process.argv);
五、总结
该问题在初次出现的时候我排查了2个多小时,可怜!
有时候一些你排查很久的问题,很有可能就是因为多了一个空格导致的,而且根据程序员敲代码的习惯性,很容易犯类似错误:即在不该有空格的情况下多加了一个空格;敲代码需要严谨与仔细。
真爱生命,戒焦戒躁,遇问题平和以待!