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

然而,有了这个:

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