commander.js 简单用例:一个文件参数
commander.js simple use case: one single file argument
我看到大多数人在处理命令行解析时都使用 commander
npm 包。我也想使用它,因为它似乎具有相当高级的功能(例如命令、帮助、选项标志等)。
然而,对于我的程序的第一个版本,我不需要这样的高级功能,我只需要指挥官解析参数,并找到提供的单个文件名(强制参数)。
我试过:
import commander = require("commander");
const cli =
commander
.version("1.0.0")
.description("Foo bar baz")
.usage('[options] <file>')
.arguments('<file>')
.action(function(file) {
if (file == null) console.log("no file")
else console.log("file was " + file);
})
.parse(process.argv);
然而,有了这个:
- 如果我不传递任何参数,则不会打印任何内容,我是在正确使用
action()
函数还是我的 null 检查有误?理想情况下,它应该打印我在这种情况下传递的 usage
字符串,并以 exitCode!=0? 结束
- 我如何检测用户是否发送了太多的文件名(太多的参数)并给她一个错误?
根据issue.
,似乎没有参数时不会执行动作函数
但是你可以像
一样检查
const cli = commander
.version('0.1.0')
.usage('[options] <file>')
.arguments('<file>')
.action(function(file) {
fileValue = file;
})
.parse(process.argv);
if (typeof fileValue === 'undefined') {
console.error('no file given!');
process.exit(1);
}
console.log('file was ' + fileValue);
我看到大多数人在处理命令行解析时都使用 commander
npm 包。我也想使用它,因为它似乎具有相当高级的功能(例如命令、帮助、选项标志等)。
然而,对于我的程序的第一个版本,我不需要这样的高级功能,我只需要指挥官解析参数,并找到提供的单个文件名(强制参数)。
我试过:
import commander = require("commander");
const cli =
commander
.version("1.0.0")
.description("Foo bar baz")
.usage('[options] <file>')
.arguments('<file>')
.action(function(file) {
if (file == null) console.log("no file")
else console.log("file was " + file);
})
.parse(process.argv);
然而,有了这个:
- 如果我不传递任何参数,则不会打印任何内容,我是在正确使用
action()
函数还是我的 null 检查有误?理想情况下,它应该打印我在这种情况下传递的usage
字符串,并以 exitCode!=0? 结束
- 我如何检测用户是否发送了太多的文件名(太多的参数)并给她一个错误?
根据issue.
,似乎没有参数时不会执行动作函数但是你可以像
一样检查const cli = commander
.version('0.1.0')
.usage('[options] <file>')
.arguments('<file>')
.action(function(file) {
fileValue = file;
})
.parse(process.argv);
if (typeof fileValue === 'undefined') {
console.error('no file given!');
process.exit(1);
}
console.log('file was ' + fileValue);