跳到主要内容

Examples

在官方例子中有更多例子,详见 Example Folder


plunder.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2)).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!

你可以使用缩略模式的 option。

short.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2)).argv;
console.log('(%d,%d)', argv.x, argv.y);

$ ./short.js -x 10 -y 21 (10,21)

甚至可以和布尔值组合使用,如下:

bool.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2)).argv;
if (argv.s) {
process.stdout.write(argv.fr ? 'Le perroquet dit: ' : 'The parrot says: ');
}
console.log(
(argv.fr ? 'couac' : 'squawk') + (argv.p ? '!' : '')
);

$ ./bool.js -s The parrot says: squawk

$ ./bool.js -sp The parrot says: squawk!

$ ./bool.js -sp --fr Le perroquet dit: couac!

也可以使用没有连字符的 option ,用 argv._ 即可!

nonopt.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2)).argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);

$ ./nonopt.js -x 6.82 -y 3.35 rum (6.82,3.35) [ 'rum' ]

$ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho (0.54,1.12) [ 'me hearties', 'yo', 'ho' ]

Yargs 也可以对 option 计数:

count.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2))
.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");

$ 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 提供 usagedemandOption 可以告诉用户如何使用你的 options ,并对 options 的格式提出要求。

area.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2))
.usage('Usage: $0 -w [num] -h [num]')
.demandOption(['w','h'])
.argv;
console.log("The area is:", argv.w * argv.h);

$ ./area.js -w 55 -h 11 The area is: 605

$ node ./area.js -w 4.91 -w 2.51 Usage: area.js -w [num] -h [num]

Options: -w [required] -h [required]

Missing required arguments: h

demandCommand 可以要求最多或最少拥有几个参数,并可以在没有满足条件时提供相应的错误信息。

demand_count.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2))
.demandCommand(2)
.argv;
console.dir(argv);

$ ./demand_count.js a

Not enough non-option arguments: got 1, need at least 2

$ ./demand_count.js a b { _: [ 'a', 'b' ], '$0': 'demand_count.js' }

$ ./demand_count.js a b c { _: [ 'a', 'b', 'c' ], '$0': 'demand_count.js' }

default 可以提供默认值:

default_singles.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2))
.default('x', 10)
.default('y', 10)
.argv
;
console.log(argv.x + argv.y);

$ ./default_singles.js -x 5 15

default_hash.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2))
.default({ x : 10, y : 10 })
.argv
;
console.log(argv.x + argv.y);

$ ./default_hash.js -y 7 17

boolean 可以将 option 解释为布尔值,但如果后面跟一个非 flag 选项,除非是 true / false,否则该字符串不会被解释为布尔值。

boolean_single.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2))
.boolean(['r','v'])
.argv
;
console.dir([ argv.r, argv.v ]);
console.dir(argv._);

$ ./boolean_single.js -r false -v "me hearties" yo ho [ false, true ] [ 'me hearties', 'yo', 'ho' ]

boolean_double.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2))
.boolean(['x','y','z'])
.argv
;
console.dir([ argv.x, argv.y, argv.z ]);
console.dir(argv._);

$ ./boolean_double.js -x -z one two three [ true, undefined, true ] [ 'one', 'two', 'three' ]


你可以描述帮助信息和设置 aliases ,Yargs 会自动生成一个格式化的帮助信息。

line_count.js:

#!/usr/bin/env node
var argv = require('yargs/yargs')(process.argv.slice(2))
.usage('Usage: $0 <command> [options]')
.command('count', 'Count the lines in a file')
.example('$0 count -f foo.js', 'count the lines in the given file')
.alias('f', 'file')
.nargs('f', 1)
.describe('f', 'Load a file')
.demandOption(['f'])
.help('h')
.alias('h', 'help')
.epilog('copyright 2019')
.argv;
var fs = require('fs');
var s = fs.createReadStream(argv.file);
var lines = 0;
s.on('data', function (buf) {
lines += buf.toString().match(/\n/g).length;
});
s.on('end', function () {
console.log(lines);
});

$ node line_count.js Usage: line_count.js <command> [options]

Commands: line_count.js count Count the lines in a file

Options: --version Show version number [boolean] -f, --file Load a file [required] -h, --help Show help [boolean]

Examples: line_count.js count -f foo.js count the lines in the given file

copyright 2019

Missing required argument: f

$ node line_count.js count line_count.js count

Count the lines in a file

Options: --version Show version number [boolean] -f, --file Load a file [required] -h, --help Show help [boolean]

Missing required argument: f

$ node line_count.js count --file line_count.js 25

$ node line_count.js count -f line_count.js 25

可以和库 inquirer 一起使用

const yargs = require('yargs');
const inquirer = require('inquirer');
const sing = () => console.log('🎵 Oy oy oy');
const askName = async () => {
const answers = await inquirer.prompt([
{
message: 'What is your name?',
name: 'name',
type: 'string'
}
]);
console.log(`Hello, ${answers.name}!`);
};
const argv = yargs(process.argv.splice(2))
.command('ask', 'use inquirer to prompt for your name', () => {}, askName)
.command('sing', 'a classic yargs command without prompting', () => {}, sing)
.demandCommand(1, 1, 'choose a command: ask or sing')
.strict()
.help('h').argv;