Commander.js收集多个选项总是包含默认值

我使用commander.jsparsing命令行参数,我试图收集可以出现多次的可选参数,它总是返回我设置的选项加上默认的选项。

function collect (val, memo) { memo.push(val); return memo; } program .command('run <param>') .action(function run(param, options) { console.log(param); console.log(options.parent.config); }); program .option('-c, --config <path>', 'Config', collect, ["/path/to/default"]) .parse(process.argv); 

当我调用这样的脚本index.js run some -c "/some/path" -c "/other/path"它打印[ '/path/to/default', '/some/path', '/other/path' ] ,它应该只打印['/some/path', '/other/path' ]

当我调用它没有-c参数它工作正常,打印与默认值的数组。

我怎样才能解决这个问题?

commander “可重复值”选项不支持默认值,至less在防止用户编写自己的逻辑来处理用户传递一个或多个值的情况下是不允许的。 你写代码的方式,你必须检查program.config属性的大小:

  • 如果用户传递一个或多个-c选项值,则大小> 1 ;
  • 否则,它是=== 1

国际海事组织,这种情况下,需要“列表”选项,它支持默认值,并为您节省一些额外的工作。 喜欢:

 program .option('-l, --list <items>', 'A list', list, [ "/path/to/default" ]) .parse(process.argv); 

要访问传递的值,只需调用program.list ,然后在命令行中使用值调用它:

 $ index.js run some -l "/some/path","/other/path" // where console.log(program.list) prints [ "/some/path", "/other/path" ] 

或者,没有价值:

 $ index.js run some // where console.log(program.list) prints [ "/path/to/default" ]