Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
The yargs npm package is a command-line argument parser that helps in building interactive command line tools, by parsing arguments and generating an elegant user interface. It provides a simple and efficient way to handle command line arguments for Node.js applications.
Command Parsing
Yargs allows you to define commands and associated options. This feature is useful for CLI applications that perform different actions based on the command provided.
const yargs = require('yargs/yargs')(process.argv.slice(2));
yargs.command('get', 'make a get HTTP request', () => {}, (argv) => {
console.log(`Request made to URL: ${argv.url}`);
}).argv;
Option Parsing
Yargs can parse options (also known as flags or switches) with additional configuration such as aliases, types, and descriptions.
const yargs = require('yargs/yargs')(process.argv.slice(2));
yargs.option('verbose', {
alias: 'v',
type: 'boolean',
description: 'Run with verbose logging'
}).argv;
Default Values
Yargs allows setting default values for options, which will be used if no value is provided by the user.
const yargs = require('yargs/yargs')(process.argv.slice(2));
yargs.default('port', 8080).argv;
Automatic Help and Version Information
Yargs can automatically generate help and version information for the CLI tool, making it easier for users to understand how to use the application.
const yargs = require('yargs/yargs')(process.argv.slice(2));
yargs.help().version().argv;
Custom Validation
Yargs provides a way to define custom validation rules for the provided arguments, ensuring that the input meets certain criteria before the application proceeds.
const yargs = require('yargs/yargs')(process.argv.slice(2));
yargs.option('port', {
describe: 'The port to bind on',
demandOption: true,
number: true
}).check((argv, options) => {
if (argv.port < 1024) {
throw new Error('Port must be at least 1024');
}
return true;
}).argv;
Commander is another popular npm package for parsing command-line options. It provides a high-level API for defining commands and options, similar to yargs. Commander is known for its simplicity and declarative approach to command-line arguments.
Minimist is a minimalistic command-line argument parser. It is more lightweight than yargs and focuses on parsing a list of arguments into an object, without the additional features like command handling, help text generation, or validation.
Meow is a CLI helper for creating Node.js command-line apps. It provides a simpler and more opinionated API compared to yargs, with built-in help text, version output, and flag aliasing. Meow is suitable for smaller projects that require less customization.
Caporal is a full-featured framework for building command-line applications. It offers a rich set of features including argument parsing, validation, autocomplete, and more. Caporal is more framework-like compared to yargs, which might be more suitable for complex CLI tools.
Yargs is a node.js library fer option parsin' fer hearties who hate option parsin'. This here module is for hearties who like all the --bells and -whistlz of program usage but think optstrings are a waste of yer time.
With yargs, option parsing doesn't have to suck (as much).
xup.js:
#!/usr/bin/env node
var argv = require('yargs').argv;
if (argv.rif - 5 * argv.xup > 7.138) {
console.log('Plunder more riffiwobbles!');
}
else {
console.log('Drop the xupptumblers!');
}
$ ./xup.js --rif=55 --xup=9.52
Plunder more riffiwobbles!
$ ./xup.js --rif 12 --xup 8.1
Drop the xupptumblers!
short.js:
#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('(%d,%d)', argv.x, argv.y);
$ ./short.js -x 10 -y 21
(10,21)
bool.js:
#!/usr/bin/env node
var util = require('util');
var argv = require('yargs').argv;
if (argv.s) {
util.print(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!
argv._
!nonopt.js:
#!/usr/bin/env node
var argv = require('yargs').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' ]
count.js
#!/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-mportant 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
divide.js:
#!/usr/bin/env node
var argv = require('yargs')
.usage('Usage: $0 -x [num] -y [num]')
.demand(['x','y'])
.argv;
console.log(argv.x / argv.y);
$ ./divide.js -x 55 -y 11
5
$ node ./divide.js -x 4.91 -z 2.51
Usage: node ./divide.js -x [num] -y [num]
Options:
-x [required]
-y [required]
Missing required arguments: y
demand_count.js: #!/usr/bin/env node var argv = require('yargs') .demandCount(2) .argv; console.dir(argv)
$ ./demand_count.js a
Not enough arguments, expected 2, but only found 1
$ ./demand_count.js a b
{ _: [ 'a', 'b' ], '$0': 'node ./demand_count.js' }
$ ./demand_count.js a b c
{ _: [ 'a', 'b', 'c' ], '$0': 'node ./demand_count.js' }
default_singles.js:
#!/usr/bin/env node
var argv = require('yargs')
.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')
.default({ x : 10, y : 10 })
.argv
;
console.log(argv.x + argv.y);
$ ./default_hash.js -y 7
17
boolean_single.js
#!/usr/bin/env node
var argv = require('yargs')
.boolean('v')
.argv
;
console.dir(argv.v);
console.dir(argv._);
$ ./boolean_single.js -v "me hearties" yo ho
true
[ 'me hearties', 'yo', 'ho' ]
boolean_double.js
#!/usr/bin/env node
var argv = require('yargs')
.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, false, true ]
[ 'one', 'two', 'three' ]
Ye can describe parameters fer help messages and set aliases. Yargs figures out how ter format a handy help string automatically.
line_count.js
#!/usr/bin/env node
var argv = require('yargs')
.usage('Count the lines in a file.\nUsage: $0')
.example('$0 -f', 'count the lines in the given file')
.demand('f')
.alias('f', 'file')
.describe('f', 'Load a file')
.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
Count the lines in a file.
Usage: node ./line_count.js
Examples:
node ./line_count.js -f count the lines in the given file
Options:
-f, --file Load a file [required]
Missing required arguments: f
$ node line_count.js --file line_count.js
20
$ node line_count.js -f line_count.js
20
By itself,
require('yargs').argv
will use process.argv
array to construct the argv
object.
You can pass in the process.argv
yourself:
require('yargs')([ '-x', '1', '-y', '2' ]).argv
or use .parse() to do the same thing:
require('yargs').parse([ '-x', '1', '-y', '2' ])
The rest of these methods below come in just before the terminating .argv
.
Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa.
Optionally .alias()
can take an object that maps keys to aliases.
Each key of this object should be the canonical version of the option, and each
value should be a string or an array of strings.
Set argv[key]
to value
if no option was specified on process.argv
.
Optionally .default()
can take an object that maps keys to default values.
If key
is a string, show the usage information and exit if key
wasn't
specified in process.argv
.
If key
is a number, demand at least as many non-option arguments, which show
up in argv._
.
If key
is an Array, demand each element.
If msg
is supplied, it will be printed when the argument is missing,
instead of the standard error message. This is especially helpful for the non-option arguments in argv._
.
Describe a key
for the generated usage information.
Optionally .describe()
can take an object that maps keys to descriptions.
Instead of chaining together .alias().demand().default()
, you can specify
keys in opt
for each of the chainable methods.
For example:
var argv = require('yargs')
.options('f', {
alias : 'file',
default : '/etc/passwd',
})
.argv
;
is the same as
var argv = require('yargs')
.alias('f', 'file')
.default('f', '/etc/passwd')
.argv
;
Optionally .options()
can take an object that maps keys to opt
parameters.
Set a usage message to show which commands to use. Inside message
, the string
$0
will get interpolated to the current script name or node command for the
present script similar to how $0
works in bash or perl.
Give some example invocations of your program. Inside cmd
, the string
$0
will get interpolated to the current script name or node command for the
present script similar to how $0
works in bash or perl.
Examples will be printed out as part of the help message.
Check that certain conditions are met in the provided arguments.
fn
is called with two arguments, the parsed argv
hash and an array of options and their aliases.
If fn
throws or returns false
, show the thrown error, usage information, and
exit.
Interpret key
as a boolean. If a non-flag option follows key
in
process.argv
, that string won't get set as the value of key
.
If key
never shows up as a flag in process.arguments
, argv[key]
will be
false
.
If key
is an Array, interpret all the elements as booleans.
Tell the parser logic not to interpret key
as a number or boolean.
This can be useful if you need to preserve leading zeros in an input.
If key
is an Array, interpret all the elements as strings.
Tells the parser to interpret key
as a path to a JSON config file. The file
is loaded and parsed, and its properties are set as arguments.
Format usage output to wrap at columns
many columns.
Return the generated usage string.
Example:
var yargs = require("yargs")
.usage("$0 -operand1 number -operand2 number -operation [add|subtract]");
console.log(yargs.help());
Later on, argv
can be retrived with yargs.argv
Print the usage data using fn
for printing.
Example:
var yargs = require("yargs")
.usage("$0 -operand1 number -operand2 number -operation [add|subtract]");
yargs.showHelp();
Later on, argv
can be retrived with yargs.argv
Parse args
instead of process.argv
. Returns the argv
object.
Get the arguments as a plain old object.
Arguments without a corresponding flag show up in the argv._
array.
The script name or node command is available at argv.$0
similarly to how $0
works in bash or perl.
Use --
to stop parsing flags and stuff the remainder into argv._
.
$ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4
{ _: [ '-c', '3', '-d', '4' ],
'$0': 'node ./examples/reflect.js',
a: 1,
b: 2 }
If you want to explicity set a field to false instead of just leaving it
undefined or to override a default you can do --no-key
.
$ node examples/reflect.js -a --no-b
{ _: [],
'$0': 'node ./examples/reflect.js',
a: true,
b: false }
Every argument that looks like a number (!isNaN(Number(arg))
) is converted to
one. This way you can just net.createConnection(argv.port)
and you can add
numbers out of argv
with +
without having that mean concatenation,
which is super frustrating.
If you specify a flag multiple times it will get turned into an array containing all the values in order.
$ node examples/reflect.js -x 5 -x 8 -x 0
{ _: [],
'$0': 'node ./examples/reflect.js',
x: [ 5, 8, 0 ] }
When you use dots (.
s) in argument names, an implicit object path is assumed.
This lets you organize arguments into nested objects.
$ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5
{ _: [],
'$0': 'node ./examples/reflect.js',
foo: { bar: { baz: 33 }, quux: 5 } }
Short numeric head -n5
style argument work too:
$ node reflect.js -n123 -m456
{ '3': true,
'6': true,
_: [],
'$0': 'node ./reflect.js',
n: 123,
m: 456 }
With npm, just do:
npm install yargs
or clone this project on github:
git clone http://github.com/chevex/yargs.git
To run the tests with expresso, just do:
expresso
This module is loosely inspired by Perl's Getopt::Casual.
FAQs
yargs the modern, pirate-themed, successor to optimist.
The npm package yargs receives a total of 34,591,932 weekly downloads. As such, yargs popularity was classified as popular.
We found that yargs demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.