#!/usr/bin/env node
var argv = require("yargs").argv;
if (argv.ships > 3 && argv.distance < 53.5) {
console.log("Plunder more riffiwobbles!");
} else {
console.log("Retreat from the xupptumblers!");
}
$ ./plunder.js --ships=4 --distance=22
Plunder more riffiwobbles!
$ ./plunder.js --ships 12 --distance 98.7
Retreat from the xupptumblers!
示例代码都来自官网:yargs
简单模式还能读取短变量如-x 4相当于argv.x = 4
简单模式还能读取布尔类型-s相当于argv.s = true
简单模式还能读取非-开始的变量,这种类型的变量保存在argv._数组里面
参数配置
简单模式的功能都只用一行代码就能实现
var argv = require("yargs").argv;
但是如果你想统计变量出现的次数怎么办? 答案就是添加参数配置选项。
#!/usr/bin/env node
var argv = require("yargs")
.count("verbose")
.alias("v", "verbose")
.argv;
VERBOSE_LEVEL = argv.verbose;
function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); }
function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); }
function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); }
WARN("Showing only important stuff");
INFO("Showing semi-important stuff too");
DEBUG("Extra chatty mode");
上面的程序能统计verbose参数出现的次数,缩写-v也会统计进去,具体调用例子参考下面的代码
$ node count.js
Showing only important stuff
$ node count.js -v
Showing only important stuff
Showing semi-important stuff too
$ node count.js -vv
Showing only important stuff
Showing semi-important stuff too
Extra chatty mode
$ node count.js -v --verbose
Showing only important stuff
Showing semi-important stuff too
Extra chatty mode
yargs
.command(
"get",
"make a get HTTP request",
function (yargs) {
return yargs.option("u", {
alias: "url",
describe: "the URL to make an HTTP request to"
})
},
function (argv) {
console.log(argv.url)
}
)
.help()
.argv
使用第三个接口需要把这个模块在多带带的文件,然后用require引入
这是模块的代码
// my-module.js
exports.command = "get [proxy]"
exports.describe = "make a get HTTP request"
exports.builder = {
banana: {
default: "cool"
},
batman: {
default: "sad"
}
}
exports.handler = function (argv) {
// do something with argv.
}
引入的时候这样使用
yargs.command(require("my-module"))
.help()
.argv
当额外的模块没有定义cmd和desc的时候可以使用第二个接口
yargs.command("get [proxy]", "make a get HTTP request", require("my-module"))
.help()
.argv
摘要:只有动手,你才能真的理解作者的构思的巧妙只有动手,你才能真正掌握一门技术持续更新中项目地址求求求源码系列跟一起学如何写函数库中高级前端面试手写代码无敌秘籍如何用不到行代码写一款属于自己的类库原理讲解实现一个对象遵循规范实战手摸手,带你用撸
Do it yourself!!!
只有动手,你才能真的理解作者的构思的巧妙
只有动手,你才能真正掌握一门技术
持续更新中……
项目地址
https...