commander.js:如何指定必需的cli参数

ask*_*ing 8 required-field command-line-arguments node.js node-commander

我正在使用commander.js包来解析命令行参数:我想使一个标志非可选,API和git repo中的测试松散地提到需要一个标志,但我通常需要被击中头部有说明.

它实际上是否可能,如果不满足要求,脚本会抛出吗?

vin*_*ayr 18

我猜这不受commander.js支持https://github.com/visionmedia/commander.js/issues/44

但你可以在你的程序中做这样的事情 -

if (!program.myoption) 
  throw new Error('--myoption required')
Run Code Online (Sandbox Code Playgroud)

  • 指挥官有“program.requiredOption()”来标记现在需要的选项。 (6认同)

小智 6

这取决于你如何写论据。

  • 有了<>它是必需的。
  • 有了[]它就不需要了。

参见示例。

const commander = require('commander')
    , program = new commander.Command()

program
   .command('autorecord')
   .argument('<title>', 'Title and file name of record') // is required
   .argument('[type]', 'Type of record. "undefined" by default') // is not required
Run Code Online (Sandbox Code Playgroud)