yargs 模块还提供3个方法,用来配置命令行参数。
demand:是否必选
default:默认值
describe:提示
#!/usr/bin/env node
var argv = require('yargs')
.demand(['n'])
.default({n: 'tom'})
.describe({n: 'your name'})
.argv;console.log('hello ', argv.n);
上面代码指定 n 参数不可省略,默认值为 tom,并给出一行提示。
options 方法允许将所有这些配置写进一个对象。
#!/usr/bin/env node
var argv = require('yargs')
.option('n', {
alias : 'name',
demand: true,
default: 'tom',
describe: 'your name',
type: 'string'
})
.argv;console.log('hello ', argv.n);
有时,某些参数不需要值,只起到一个开关作用,这时可以用 boolean 方法指定这些参数返回布尔值。
#!/usr/bin/env node
var argv = require('yargs')
.boolean(['n'])
.argv;console.log('hello ', argv.n);
上面代码中,参数 n 总是返回一个布尔值,用法如下。
$ hello
hello false
$ hello -n
hello true
$ hello -n tom
hello trueboolean 方法也可以作为属性,写入 option 对象。
#!/usr/bin/env node
var argv = require('yargs')
.option('n', {
boolean: true
})
.argv;console.log('hello ', argv.n);
七、帮助信息
yargs 模块提供以下方法,生成帮助信息。
usage:用法格式
example:提供例子
help:显示帮助信息
epilog:出现在帮助信息的结尾
#!/usr/bin/env node
var argv = require('yargs')
.option('f', {
alias : 'name',
demand: true,
default: 'tom',
describe: 'your name',
type: 'string'
})
.usage('Usage: hello [options]')
.example('hello -n tom', 'say hello to Tom')
.help('h')
.alias('h', 'help')
.epilog('copyright 2015')
.argv;console.log('hello ', argv.n);
执行结果如下。
$ hello -hUsage: hello [options]
Options:
-f, --name your name [string] [required] [default: "tom"] -h, --help Show help [boolean]
Examples:
hello -n tom say hello to Tom
copyright 2015
八、子命令
yargs 模块还允许通过 command 方法,设置 Git 风格的子命令。
#!/usr/bin/env node
var argv = require('yargs')
.command("morning", "good morning", function (yargs) {









