command-line-args值得一看!
您可以使用主要符号标准 (learn more) 设置选项。这些命令都是等效的,设置相同的值:
$ example --verbose --timeout=1000 --src one.js --src two.js
$ example --verbose --timeout 1000 --src one.js two.js
$ example -vt 1000 --src one.js two.js
$ example -vt 1000 one.js two.js
要访问这些值,首先创建一个option definitions 列表,描述您的应用程序接受的选项。 type 属性是一个 setter 函数(提供的值通过 this 传递),让您可以完全控制接收到的值。
const optionDefinitions = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'src', type: String, multiple: true, defaultOption: true },
{ name: 'timeout', alias: 't', type: Number }
]
接下来,使用commandLineArgs()解析选项:
const commandLineArgs = require('command-line-args')
const options = commandLineArgs(optionDefinitions)
options 现在看起来像这样:
{
src: [
'one.js',
'two.js'
],
verbose: true,
timeout: 1000
}
高级用法
除了上述典型用法,您还可以配置 command-line-args 以接受更高级的语法形式。
Command-based syntax(git 风格)的形式:
$ executable <command> [options]
例如。
$ git commit --squash -m "This is my commit message"
Command and sub-command syntax(码头风格)的形式:
$ executable <command> [options] <sub-command> [options]
例如。
$ docker run --detached --image centos bash -c yum install -y httpd
使用指南生成
可以使用command-line-usage 生成使用指南(通常在设置--help 时打印)。有关如何创建它们的说明,请参阅下面的示例和 read the documentation。
一个典型的使用指南示例。
polymer-cli 使用指南是一个很好的现实示例。
进一步阅读
还有很多要学习的内容,请参阅 the wiki 获取示例和文档。