- 参数基础
- 定义参数
- 转换
- 定义命令
- 其他
参数基础
argv就是process.argv,也可以用parse(),无参数时效果一样:_里存放不带-横杠或–双横杠的参数。$0是命令脚本
require('yargs').argv; require('yargs').parse(); // 和上面等价 // node base.js { _: [], '$0': 'base.js' } // node base.js -a=2 { _: [], a: 2, '$0': 'base.js' }
你也可以自己传参数(也可以用parse()传参数,效果一样):
require('yargs')([ '-x', '1', '-y', '2' ]).argv; require('yargs').parse([ '-x', '1', '-y', '2' ]); // 和上面等价 // node base.js { _: [], x: 1, y: 2, '$0': 'base.js' }
.array(key):定义参数数组
require('yargs').array('foo').argv; // noode yargs.js --foo foo bar { _: [], foo: [ 'foo', 'bar' ], '$0': 'base.js' }
.default(key, value, [description]):提供默认参数
const argv = require('yargs') .default('random', () => { return Math.random() * 256; }) .argv; console.log(argv); // node base.js { _: [], random: 250.64659976268666, '$0': 'yargs.js' } // node base.js --random 24 { _: [], random: 24, '$0': 'yargs.js' }
定义参数
通常一系列API链式调用来定义参数。例如:
.alias(key, alias):定义别名
.describe(key, desc):定义命令描述
.choices(key, choices):定义选项的固定值
.demandOption(key, msg):定义必需的参数
.fail(fn):出错时可以自定义异常处理
.help([option, [description]]):定义help选项
const argv = require('yargs') .alias('i', 'ingredient') .describe('i', 'choose your sandwich ingredients') .choices('i', ['peanut-butter', 'jelly', 'banana', 'pickles']) .demandOption(['i'], '-i is require') // 定义必需的参数,用户不传会报错 .help('h') // 执行 node base.js --h 或 --help(默认支持)能获取到帮助信息 .fail((msg, err, yargs) => { if (err) throw err; console.error('请输入参数 -i'); console.error(msg); console.error('参数释义 \n', yargs.help()); process.exit(1); }) .argv;
上面这种链式调用太麻烦,可以用.options(key, [opt]),效果一样的,支持的opt点这里
const argv = require('yargs') .option('ingredient', { alias: 'i', describe: 'choose your sandwich ingredients', choices: ['peanut-butter', 'jelly', 'banana', 'pickles'], demandOption: true // 设为 true }) .help('h') .fail((msg, err, yargs) => { if (err) throw err; console.error('请输入参数 -i'); console.error(msg); console.error('参数释义 \n', yargs.help()); process.exit(1); }) .argv;
转换
.coerce(key, fn):可以转换获取到的value值
const argv = require('yargs') .coerce('file', arg => { return require('fs').readFileSync(arg, 'utf8'); }) .argv; console.log(argv); // node base.js --file '../tmp/foo.js' // { _: [], file: '// 这是一个测试用文件\nvar foo = \'foo\';', '$0': 'yargs.js' } const argv = require('yargs') .option('user') .coerce('user', opt => { opt.name = opt.name.toLowerCase(); opt.password = '[SECRET]'; return opt; }) .argv; console.log(argv); // node base.js --user.name Batman --user.password 123 // { _: [], user: { name: 'batman', password: '[SECRET]' }, '$0': 'yargs.js' }
定义命令
.command(cmd, desc, [builder], [handler]):定义可执行的命令
const argv = require('yargs') .command( 'get', 'make a get HTTP request', yargs => { // builder 的参数是 yargs 的实例 return yargs.option('u', { alias: 'url', describe: 'the URL to make an HTTP request to', default: 'http://yargs.js.org/' }) }, argv => { // 回调函数的参数是 argv 对象 console.log(argv.url) } ) .help() .argv; // node base.js get 打印出:http://yargs.js.org/ // node base.js get -u https://zxljack.com 打印出:https://zxljack.com
.demandCommand([min=1], [max], [minMsg], [maxMsg]):定义必需的命令
const argv = require('yargs') .command({ command: 'configure [value]', aliases: ['config', 'cfg'], desc: 'Set a config variable', builder: yargs => yargs.default('value', 'true'), handler: argv => { console.log(`setting key:${argv.key} value:${argv.value}`); } }) .demandCommand(1, 'You need at least one command before moving on') .help() .argv; // node base.js 会提示报错 // node base.js cfg name jack setting key:name value:jack
.positional(key, opt):允许你在[builder]内定义占位参数,必需的占位参数形式为<foo>,可选的占位参数形式为[bar]。支持的很多opt
const argv = require('yargs') .command('run <port> <guid>', 'run the server', yargs => { yargs.positional('guid', { // 定义占位参数 describe: 'a unique identifier for the server', type: 'string' }) }).argv; console.log(argv); // node base.js run 8080 abcd // { _: [ 'run' ], '$0': 'base.js', port: 8080, guid: 'abcd' }
另外,占位参数支持用 | 提供多个别名,例如第一个参数允许是用户名或邮箱名。最后一个占位参数支持多个,用 .. 操作符表示,例如[files..]支持上传多个文件。
const argv = require('yargs') .command('get <username|email> [password]', 'fetch a user by username or email.') .help() .argv; console.log(argv); // node base.js get jack aaa // { _: [ 'get' ], '$0': 'base.js', username: 'jack', email: 'jack', password: 'aaa' } const argv = require('yargs') .command('download <url> [files..]', 'download several files') .help() .argv; console.log(argv); // node base.js download www.abc.com bb.js cc.png // { _: [ 'download' ], '$0': 'base.js', url: 'www.abc.com', files: [ 'bb.js', 'cc.png' ] }
.middleware(callbacks, [applyBeforeValidation]):命令支持中间件形式,第二个参数applyBeforeValidation设为true,表示在验证参数前执行。
const mwFunc1 = argv => console.log('第一个中间件'); const mwFunc2 = argv => console.log('第二个中间件'); const argv = yargs .command('get', '自定义命令', {}, argv => { console.log('执行命令'); }) .middleware([mwFunc1, mwFunc2]) .argv; // node base.js get // 第一个中间件 // 第二个中间件 // 执行命令 const argv = yargs .middleware(function (argv) { if (process.env.HOME) argv.home = process.env.HOME }, true) .command('configure-home', "do something with a user's home directory", { 'home': { 'demand': true, 'string': true } }, function(argv) { console.info(`用户目录是: ${argv.home}`); } ) .argv; // node base.js configure-home // 用户目录是: /Users/jack
其他
.scriptName($0):设置$0,即命令脚本,即process.argv[1]
var yargs = require("yargs") .scriptName("my-script") .help() .argv;
PS:从开始到放弃,实在太多了,觉累不爱,剩下这些,自己过了一遍,等实际用到再逐个详细补充到上面
.boolean(key)
.check(fn, [global=true])
.completion([cmd], [description], [fn])
.conflicts(x, y)
.count(key)
.hide(key)
.showHidden([option, [description]])
.detectLocale(boolean)
.env([prefix])
.epilog(str)
.example(cmd, desc)
.exitProcess(enable)
.exit(code, err)
.getCompletion(args, done);
.global(globals, [global=true])
.group(key(s), groupName)
.implies(x, y)
.nargs(key, count)
.normalize(key)
.number(key)
.parse([args], [context], [parseCallback])
.parsed
.parserConfiguration(obj)
.recommendCommands()
.requiresArg(key)
.showCompletionScript()
.showHelp(consoleLevel=’error’)
.showHelpOnFail(enable, [message])
.skipValidation(key)
.strict([enabled=true])
.string(key)
.updateStrings(obj)
.usage(
.version([option], [description], [version])
.wrap(columns)