yargs(WIP)

yargs 是一个帮助你构建可交互的命令工具,通过解析参数和生成优雅的用户界面。

Demo

简单案例

#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
const argv = yargs(hideBin(process.argv)).argv
if (argv.ships > 3 && argv.distance < 53.5) {
console.log('Plunder more riffiwobbles!')
} else {
console.log('Retreat from the xupptumblers!')
}

hideBinprocess.argv.slice(2)的缩写

process.argv

process.argv属性返回数组,其中包含启动 Node.js 进程传入的命令行参数。第一个元素将是 process.execPath。如果需要访问 argv[0] 原始值,请参阅 process.argv0。第二个元素将是正在执行的 JavaScript 文件的路径。其余元素将是任何其他命令行参数。

假如,假设 process-args.js 有以下脚本:

import { argv } from 'process'
// 打印 process.argv
argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
})

以如下方式启动 Node.js 进程

$ node process-args.js one two=three four

将生成输出:

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four

API

.alias(key, alias)

.argv

.array(key)

.boolean(key)

.check(fn, [global=true])

.choices(key, choices)

.coerce(key, fn)

.commandDir(directory, [opts])

.command(cmd, desc, [builder], [handler])

.command(cmd, desc, [module])

.command(module)

.completion([cmd], [description], [fn])

.config([key], [description], [parseFn])

.config(object)

.conflicts(x, y)

.count(key)

.default(key, value, [description])

.demandOption(key, [msg | boolean])

.demandOption(key, msg)

.demandCommand([min=1], [max], [minMsg], [maxMsg])

.deprecateOption(key, [msg | boolean])

.describe(key, desc)

.hide(key)

.detectLocale(boolean)

.env([prefix])

.epilog(str)

.example(cmd, desc)

.example([[cmd1, desc1], [cmd2, desc2], ...])

.exitProcess(enable)

.exit(code, err)

.fail(fn | boolean)

.getCompletion(args, done);

.getHelp()

.global(globals, [global=true])

.group(key(s), groupName)

.help()

.help([option | boolean])

.help([option, [description]])

.implies(x, y)

.locale()

.locale(locale)

.middleware(callbacks, [appleBeforeValidation])

.nargs(key, count)

.normalize(key)

.number(key)

.option(key, [opt])

.options(key,[opt])

.parse([args],[context],[parseCallback])

.parseAsync([args],[context],[parseCallback])

.parseSync([args], [context], [parseCallback])

.parserConfiguration(obj)

.pkgConf(key, [cwd])

.positional(key, opt)

.recommendCommands()

.require(key, [msg | boolean])

.required(key, [msg | boolean])

.requiresArg(key)

.scriptName($0)

.showCompletionScript()

.showHelp([consoleLevel | printCallback])

.showVersion([consoleLevel | printCallback])

.showHelpOnFail(enable, [message])

.showHidden()

.showHidden([option | boolean])

.showHidden([option, [description]])

.skipValidation(key)

.strict([enabled=true])

.strictCommands([enabled=true])

.strictOptions([enabled=true])

.string(key)

.updateLocale(obj)

.updateStrings(obj)

.usage(, [desc], [builder], [handler])

.version()

.version([version|boolean])

.version([option], [description],[version])

.wrap(columns)

参考资料