4 Yargs be a node.js library fer hearties tryin' ter parse optstrings.
6 With yargs, ye be havin' a map that leads straight to yer treasure! Treasure of course, being a simple option hash.
8 [![Build Status][travis-image]][travis-url]
9 [![Dependency Status][gemnasium-image]][gemnasium-url]
10 [![Coverage Status][coveralls-image]][coveralls-url]
11 [![NPM version][npm-image]][npm-url]
12 [![Windows Tests][windows-image]][windows-url]
13 [![js-standard-style][standard-image]][standard-url]
14 [![standard-version][standard-version-image]][standard-version-url]
16 > Yargs is the official successor to optimist. Please feel free to submit issues and pull requests. If you'd like to contribute and don't know where to start, have a look at [the issue list](https://github.com/yargs/yargs/issues) :)
21 With yargs, the options be just a hash!
22 -------------------------------------------------------------------
28 var argv = require('yargs').argv;
30 if (argv.ships > 3 && argv.distance < 53.5) {
31 console.log('Plunder more riffiwobbles!');
33 console.log('Retreat from the xupptumblers!');
39 $ ./plunder.js --ships=4 --distance=22
40 Plunder more riffiwobbles!
42 $ ./plunder.js --ships 12 --distance 98.7
43 Retreat from the xupptumblers!
45 ![Joe was one optimistic pirate.](http://i.imgur.com/4WFGVJ9.png)
47 But don't walk the plank just yet! There be more! You can do short options:
48 -------------------------------------------------
54 var argv = require('yargs').argv;
55 console.log('(%d,%d)', argv.x, argv.y);
60 $ ./short.js -x 10 -y 21
63 And booleans, both long, short, and even grouped:
64 ----------------------------------
70 var argv = require('yargs').argv;
73 process.stdout.write(argv.fr ? 'Le perroquet dit: ' : 'The parrot says: ');
76 (argv.fr ? 'couac' : 'squawk') + (argv.p ? '!' : '')
83 The parrot says: squawk
86 The parrot says: squawk!
89 Le perroquet dit: couac!
91 And non-hyphenated options too! Just use `argv._`!
92 -------------------------------------------------
98 var argv = require('yargs').argv;
99 console.log('(%d,%d)', argv.x, argv.y);
105 $ ./nonopt.js -x 6.82 -y 3.35 rum
109 $ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho
111 [ 'me hearties', 'yo', 'ho' ]
113 Yargs even counts your booleans!
114 ----------------------------------------------------------------------
120 var argv = require('yargs')
122 .alias('v', 'verbose')
125 VERBOSE_LEVEL = argv.verbose;
127 function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); }
128 function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); }
129 function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); }
131 WARN("Showing only important stuff");
132 INFO("Showing semi-important stuff too");
133 DEBUG("Extra chatty mode");
138 Showing only important stuff
141 Showing only important stuff
142 Showing semi-important stuff too
145 Showing only important stuff
146 Showing semi-important stuff too
149 $ node count.js -v --verbose
150 Showing only important stuff
151 Showing semi-important stuff too
154 Tell users how to use yer options and make demands.
155 -------------------------------------------------
161 var argv = require('yargs')
162 .usage('Usage: $0 -w [num] -h [num]')
166 console.log("The area is:", argv.w * argv.h);
171 $ ./area.js -w 55 -h 11
174 $ node ./area.js -w 4.91 -w 2.51
175 Usage: area.js -w [num] -h [num]
181 Missing required arguments: h
183 After yer demands have been met, demand more! Ask for non-hyphenated arguments!
184 -----------------------------------------
190 var argv = require('yargs')
198 $ ./demand_count.js a
200 Not enough non-option arguments: got 1, need at least 2
202 $ ./demand_count.js a b
203 { _: [ 'a', 'b' ], '$0': 'demand_count.js' }
205 $ ./demand_count.js a b c
206 { _: [ 'a', 'b', 'c' ], '$0': 'demand_count.js' }
208 EVEN MORE SHIVER ME TIMBERS!
215 var argv = require('yargs')
220 console.log(argv.x + argv.y);
225 $ ./default_singles.js -x 5
232 var argv = require('yargs')
233 .default({ x : 10, y : 10 })
236 console.log(argv.x + argv.y);
241 $ ./default_hash.js -y 7
244 And if you really want to get all descriptive about it...
245 ---------------------------------------------------------
251 var argv = require('yargs')
261 $ ./boolean_single.js -v "me hearties" yo ho
263 [ 'me hearties', 'yo', 'ho' ]
270 var argv = require('yargs')
271 .boolean(['x','y','z'])
274 console.dir([ argv.x, argv.y, argv.z ]);
280 $ ./boolean_double.js -x -z one two three
281 [ true, false, true ]
282 [ 'one', 'two', 'three' ]
284 Yargs is here to help you...
285 ---------------------------
287 Ye can describe parameters fer help messages and set aliases. Yargs figures
288 out how ter format a handy help string automatically.
294 var argv = require('yargs')
295 .usage('Usage: $0 <command> [options]')
296 .command('count', 'Count the lines in a file')
298 .example('$0 count -f foo.js', 'count the lines in the given file')
302 .describe('f', 'Load a file')
305 .epilog('copyright 2015')
308 var fs = require('fs');
309 var s = fs.createReadStream(argv.file);
312 s.on('data', function (buf) {
313 lines += buf.toString().match(/\n/g).length;
316 s.on('end', function () {
322 $ node line_count.js count
323 Usage: line_count.js <command> [options]
326 count Count the lines in a file
329 -f, --file Load a file [required]
330 -h, --help Show help [boolean]
333 line_count.js count -f foo.js count the lines in the given file
337 Missing required arguments: f
339 $ node line_count.js count --file line_count.js
342 $ node line_count.js count -f line_count.js
351 require('yargs').argv
354 will use the `process.argv` array to construct the `argv` object.
356 You can pass in the `process.argv` yourself:
359 require('yargs')([ '-x', '1', '-y', '2' ]).argv
362 or use `.parse()` to do the same thing:
365 require('yargs').parse([ '-x', '1', '-y', '2' ])
368 The rest of these methods below come in just before the terminating `.argv`.
370 <a name="alias"></a>.alias(key, alias)
373 Set key names as equivalent such that updates to a key will propagate to aliases
376 Optionally `.alias()` can take an object that maps keys to aliases.
377 Each key of this object should be the canonical version of the option, and each
378 value should be a string or an array of strings.
383 Get the arguments as a plain old object.
385 Arguments without a corresponding flag show up in the `argv._` array.
387 The script name or node command is available at `argv.$0` similarly to how `$0`
388 works in bash or perl.
390 If `yargs` is executed in an environment that embeds node and there's no script name (e.g.
391 [Electron](http://electron.atom.io/) or [nw.js](http://nwjs.io/)), it will ignore the first parameter since it
392 expects it to be the script name. In order to override this behavior, use `.parse(process.argv.slice(1))`
393 instead of `.argv` and the first parameter won't be ignored.
395 <a name="array"></a>.array(key)
398 Tell the parser to interpret `key` as an array. If `.array('foo')` is set,
399 `--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`.
401 <a name="boolean"></a>.boolean(key)
404 Interpret `key` as a boolean. If a non-flag option follows `key` in
405 `process.argv`, that string won't get set as the value of `key`.
407 `key` will default to `false`, unless a `default(key, undefined)` is
410 If `key` is an array, interpret all the elements as booleans.
415 Check that certain conditions are met in the provided arguments.
417 `fn` is called with two arguments, the parsed `argv` hash and an array of options and their aliases.
419 If `fn` throws or returns a non-truthy value, show the thrown error, usage information, and
422 <a name="choices"></a>.choices(key, choices)
423 ----------------------
425 Limit valid values for `key` to a predefined set of `choices`, given as an array
426 or as an individual value.
429 var argv = require('yargs')
430 .alias('i', 'ingredient')
431 .describe('i', 'choose your sandwich ingredients')
432 .choices('i', ['peanut-butter', 'jelly', 'banana', 'pickles'])
437 If this method is called multiple times, all enumerated values will be merged
438 together. Choices are generally strings or numbers, and value matching is
441 Optionally `.choices()` can take an object that maps multiple keys to their
444 Choices can also be specified as `choices` in the object given to `option()`.
447 var argv = require('yargs')
450 describe: 'choose a size',
451 choices: ['xs', 's', 'm', 'l', 'xl']
456 .command(cmd, desc, [builder], [handler])
457 -----------------------------------------
458 .command(cmd, desc, [module])
459 -----------------------------
463 Document the commands exposed by your application.
465 Use `desc` to provide a description for each command your application accepts (the
466 values stored in `argv._`). Set `desc` to `false` to create a hidden command.
467 Hidden commands don't show up in the help output and aren't available for
470 Optionally, you can provide a `builder` object to give hints about the
471 options that your command accepts:
474 yargs.command('get', 'make a get HTTP request', {
477 default: 'http://yargs.js.org/'
484 Note that commands will not automatically inherit configuration _or_ options
485 of their parent context. This means you'll have to re-apply configuration
486 if necessary, and make options global manually using the [global](#global) method.
488 Additionally, the [`help`](#help) and [`version`](#version)
489 options (if used) **always** apply globally, just like the
490 [`.wrap()`](#wrap) configuration.
492 `builder` can also be a function. This function is executed
493 with a `yargs` instance, and can be used to provide _advanced_ command specific help:
496 yargs.command('get', 'make a get HTTP request', function (yargs) {
497 return yargs.option('url', {
499 default: 'http://yargs.js.org/'
506 You can also provide a handler function, which will be executed with the
507 parsed `argv` object:
513 'make a get HTTP request',
515 return yargs.option('u', {
517 describe: 'the URL to make an HTTP request to'
521 console.log(argv.url)
528 ### Positional Arguments
530 Commands can accept _optional_ and _required_ positional arguments. Required
531 positional arguments take the form `<foo>`, and optional arguments
532 take the form `[bar]`. The parsed positional arguments will be populated in
536 yargs.command('get <source> [proxy]', 'make a get HTTP request')
541 #### Variadic Positional Arguments
543 The last positional argument can optionally accept an array of
544 values, by using the `..` operator:
547 yargs.command('download <url> [files..]', 'download several files')
552 ### Providing a Command Module
554 For complicated commands you can pull the logic into a module. A module
555 simply needs to export:
557 * `exports.command`: string that executes this command when given on the command line, may contain positional args
558 * `exports.describe`: string used as the description for the command in help text, use `false` for a hidden command
559 * `exports.builder`: object declaring the options the command accepts, or a function accepting and returning a yargs instance
560 * `exports.handler`: a function which will be passed the parsed argv.
564 exports.command = 'get <source> [proxy]'
566 exports.describe = 'make a get HTTP request'
577 exports.handler = function (argv) {
578 // do something with argv.
582 You then register the module like so:
585 yargs.command(require('my-module'))
590 Or if the module does not export `command` and `describe` (or if you just want to override them):
593 yargs.command('get <source> [proxy]', 'make a get HTTP request', require('my-module'))
598 .commandDir(directory, [opts])
599 ------------------------------
601 Apply command modules from a directory relative to the module calling this method.
603 This allows you to organize multiple commands into their own modules under a
604 single directory and apply all of them at once instead of calling
605 `.command(require('./dir/module'))` multiple times.
607 By default, it ignores subdirectories. This is so you can use a directory
608 structure to represent your command hierarchy, where each command applies its
609 subcommands using this method in its builder function. See the example below.
611 Note that yargs assumes all modules in the given directory are command modules
612 and will error if non-command modules are encountered. In this scenario, you
613 can either move your module to a different directory or use the `exclude` or
614 `visit` option to manually filter it out. More on that below.
616 `directory` is a relative directory path as a string (required).
618 `opts` is an options object (optional). The following options are valid:
620 - `recurse`: boolean, default `false`
622 Look for command modules in all subdirectories and apply them as a flattened
623 (non-hierarchical) list.
625 - `extensions`: array of strings, default `['js']`
627 The types of files to look for when requiring command modules.
631 A synchronous function called for each command module encountered. Accepts
632 `commandObject`, `pathToFile`, and `filename` as arguments. Returns
633 `commandObject` to include the command; any falsy value to exclude/skip it.
635 - `include`: RegExp or function
637 Whitelist certain modules. See [`require-directory` whitelisting](https://www.npmjs.com/package/require-directory#whitelisting) for details.
639 - `exclude`: RegExp or function
641 Blacklist certain modules. See [`require-directory` blacklisting](https://www.npmjs.com/package/require-directory#blacklisting) for details.
643 ### Example command hierarchy using `.commandDir()`
650 $ myapp remote --help
651 $ myapp remote add base http://yargs.js.org
652 $ myapp remote prune base
653 $ myapp remote prune base fork whatever
683 exports.command = 'init [dir]'
684 exports.desc = 'Create an empty repo'
690 exports.handler = function (argv) {
691 console.log('init called for dir', argv.dir)
698 exports.command = 'remote <command>'
699 exports.desc = 'Manage set of tracked repos'
700 exports.builder = function (yargs) {
701 return yargs.commandDir('remote_cmds')
703 exports.handler = function (argv) {}
706 cmds/remote_cmds/add.js:
709 exports.command = 'add <name> <url>'
710 exports.desc = 'Add remote named <name> for repo at url <url>'
712 exports.handler = function (argv) {
713 console.log('adding remote %s at url %s', argv.name, argv.url)
717 cmds/remote_cmds/prune.js:
720 exports.command = 'prune <name> [names..]'
721 exports.desc = 'Delete tracked branches gone stale for remotes'
723 exports.handler = function (argv) {
724 console.log('pruning remotes %s', [].concat(argv.name).concat(argv.names).join(', '))
728 .completion([cmd], [description], [fn])
729 ---------------------------------------
731 Enable bash-completion shortcuts for commands and options.
733 `cmd`: When present in `argv._`, will result in the `.bashrc` completion script
734 being outputted. To enable bash completions, concat the generated script to your
735 `.bashrc` or `.bash_profile`.
737 `description`: Provide a description in your usage instructions for the command
738 that generates bash completion scripts.
740 `fn`: Rather than relying on yargs' default completion functionality, which
741 shiver me timbers is pretty awesome, you can provide your own completion
744 If invoked without parameters, `.completion()` will make `completion` the command to output
745 the completion script.
748 var argv = require('yargs')
749 .completion('completion', function(current, argv) {
750 // 'current' is the current command being completed.
751 // 'argv' is the parsed arguments so far.
752 // simply return an array of completions.
761 You can also provide asynchronous completions.
764 var argv = require('yargs')
765 .completion('completion', function(current, argv, done) {
766 setTimeout(function() {
776 But wait, there's more! You can return an asynchronous promise.
779 var argv = require('yargs')
780 .completion('completion', function(current, argv, done) {
781 return new Promise(function (resolve, reject) {
782 setTimeout(function () {
783 resolve(['apple', 'banana'])
790 <a name="config"></a>.config([key], [description], [parseFn])
791 -------------------------------------------------------------
795 Tells the parser that if the option specified by `key` is passed in, it
796 should be interpreted as a path to a JSON config file. The file is loaded
797 and parsed, and its properties are set as arguments.
799 If invoked without parameters, `.config()` will make `--config` the option to pass the JSON config file.
801 An optional `description` can be provided to customize the config (`key`) option
804 An optional `parseFn` can be used to provide a custom parser. The parsing
805 function must be synchronous, and should return an object containing
806 key value pairs or an error.
809 var argv = require('yargs')
810 .config('settings', function (configPath) {
811 return JSON.parse(fs.readFileSync(configPath, 'utf-8'))
816 You can also pass an explicit configuration `object`, it will be parsed
817 and its properties will be set as arguments.
820 var argv = require('yargs')
821 .config({foo: 1, bar: 2})
834 <a name="count"></a>.count(key)
837 Interpret `key` as a boolean flag, but set its parsed value to the number of
838 flag occurrences rather than `true` or `false`. Default value is thus `0`.
840 <a name="default"></a>.default(key, value, [description])
841 ---------------------------------------------------------
842 .defaults(key, value, [description])
843 ------------------------------------
845 **Note:** The `.defaults()` alias is deprecated. It will be
846 removed in the next major version.
848 Set `argv[key]` to `value` if no option was specified in `process.argv`.
850 Optionally `.default()` can take an object that maps keys to default values.
852 But wait, there's more! The default value can be a `function` which returns
853 a value. The name of the function will be used in the usage string:
856 var argv = require('yargs')
857 .default('random', function randomValue() {
858 return Math.random() * 256;
862 Optionally, `description` can also be provided and will take precedence over
863 displaying the value in the usage instructions:
866 .default('timeout', 60000, '(one-minute)')
869 <a name="demand"></a>.demand(key, [msg | boolean])
870 ------------------------------
871 .demand(count, [max], [msg])
872 ------------------------------
874 If `key` is a string, show the usage information and exit if `key` wasn't
875 specified in `process.argv`.
877 If `key` is a number, demand at least as many non-option arguments, which show
878 up in `argv._`. A second number can also optionally be provided, which indicates
879 the maximum number of non-option arguments.
881 If `key` is an array, demand each element.
883 If a `msg` string is given, it will be printed when the argument is missing,
884 instead of the standard error message. This is especially helpful for the non-option arguments in `argv._`.
886 If a `boolean` value is given, it controls whether the option is demanded;
887 this is useful when using `.options()` to specify command line parameters.
889 A combination of `.demand(1)` and `.strict()` will allow you to require a user to pass at least one command:
892 var argv = require('yargs')
893 .command('install', 'tis a mighty fine package to install')
899 Similarly, you can require a command and arguments at the same time:
902 var argv = require('yargs')
903 .command('install', 'tis a mighty fine package to install')
904 .demand(1, ['w', 'm'])
909 <a name="describe"></a>.describe(key, desc)
912 Describe a `key` for the generated usage information.
914 Optionally `.describe()` can take an object that maps keys to descriptions.
916 .detectLocale(boolean)
919 Should yargs attempt to detect the os' locale? Defaults to `true`.
924 Tell yargs to parse environment variables matching the given prefix and apply
925 them to argv as though they were command line arguments.
927 Use the "__" separator in the environment variable to indicate nested options.
928 (e.g. prefix_nested__foo => nested.foo)
930 If this method is called with no argument or with an empty string or with `true`,
931 then all env vars will be applied to argv.
933 Program arguments are defined in this order of precedence:
938 4. Configured defaults
941 var argv = require('yargs')
944 alias: 'fruit-thing',
955 'fruit-thing': 'apple',
961 $ MY_PROGRAM_FRUIT_THING=banana node fruity.js
963 fruitThing: 'banana',
965 'fruit-thing': 'banana',
970 $ MY_PROGRAM_FRUIT_THING=banana node fruity.js -f cat
973 'fruit-thing': 'cat',
978 Env var parsing is disabled by default, but you can also explicitly disable it
979 by calling `.env(false)`, e.g. if you need to undo previous configuration.
986 A message to print at the end of the usage instructions, e.g.
989 var argv = require('yargs')
990 .epilogue('for more information, find our manual at http://example.com');
996 Give some example invocations of your program. Inside `cmd`, the string
997 `$0` will get interpolated to the current script name or node command for the
998 present script similar to how `$0` works in bash or perl.
999 Examples will be printed out as part of the help message.
1001 .exitProcess(enable)
1002 ----------------------------------
1004 By default, yargs exits the process when the user passes a help flag, uses the
1005 `.version` functionality, or when validation fails. Calling
1006 `.exitProcess(false)` disables this behavior, enabling further actions after
1007 yargs have been validated.
1012 Method to execute when a failure occurs, rather than printing the failure message.
1014 `fn` is called with the failure message that would have been printed and the
1015 `Error` instance originally thrown, if any.
1018 var argv = require('yargs')
1019 .fail(function (msg, err) {
1020 if (err) throw err // preserve stack
1021 console.error('You broke it!')
1028 .getCompletion(args, done);
1029 ---------------------------
1031 Allows to programmatically get completion choices for any line.
1033 `args`: An array of the words in the command line to complete.
1035 `done`: The callback to be called with the resulting completions.
1041 .option('foobar', {})
1042 .option('foobaz', {})
1044 .getCompletion(['./test.js', '--foo'], function (completions) {
1045 console.log(completions)
1049 Outputs the same completion choices as `./test.js --foo`<kbd>TAB</kbd>: `--foobar` and `--foobaz`
1051 <a name="global"></a>.global(globals)
1054 Indicate that an option (or group of options) should not be reset when a command
1055 is executed, as an example:
1058 var argv = require('yargs')
1067 .command('foo', 'foo command', function (yargs) {
1068 return yargs.option('b', {
1077 If the `foo` command is executed the `all` option will remain, but the `none`
1078 option will have been eliminated.
1080 `help`, `version`, and `completion` options default to being global.
1082 <a name="group"></a>.group(key(s), groupName)
1083 --------------------
1085 Given a key, or an array of keys, places options under an alternative heading
1086 when displaying usage instructions, e.g.,
1089 var yargs = require('yargs')(['--help'])
1091 .group('batman', 'Heroes:')
1092 .describe('batman', "world's greatest detective")
1098 --batman world's greatest detective
1101 --help Show help [boolean]
1103 <a name="help"></a>.help([option, [description]])
1104 ------------------------------
1106 Add an option (e.g. `--help`) that displays the usage string and exits the
1107 process. If present, the `description` parameter customizes the description of
1108 the help option in the usage string.
1110 If invoked without parameters, `.help()` will make `--help` the option to trigger
1116 var yargs = require("yargs")(['--help'])
1117 .usage("$0 -operand1 number -operand2 number -operation [add|subtract]")
1122 Later on, `argv` can be retrieved with `yargs.argv`.
1127 Given the key `x` is set, it is required that the key `y` is set.
1129 Optionally `.implies()` can accept an object specifying multiple implications.
1134 Return the locale that yargs is currently using.
1136 By default, yargs will auto-detect the operating system's locale so that
1137 yargs-generated help content will display in the user's language.
1139 To override this behavior with a static locale, pass the desired locale as a
1140 string to this method (see below).
1145 Override the auto-detected locale from the user's operating system with a static
1146 locale. Note that the OS locale can be modified by setting/exporting the `LC_ALL`
1147 environment variable.
1150 var argv = require('yargs')
1151 .usage('./$0 - follow ye instructions true')
1154 describe: "'tis a mighty fine option",
1157 .command('run', "Arrr, ya best be knowin' what yer doin'")
1158 .example('$0 run foo', "shiver me timbers, here's an example for ye")
1168 ./test.js - follow ye instructions true
1171 run Arrr, ya best be knowin' what yer doin'
1173 Options for me hearties!
1174 --option, -o 'tis a mighty fine option [requi-yar-ed]
1175 --help Parlay this here code of conduct [boolean]
1178 test.js run foo shiver me timbers, here's an example for ye
1180 Ye be havin' to set the followin' argument land lubber: option
1183 Locales currently supported:
1186 * **en:** American English.
1189 * **id:** Indonesian.
1193 * **nb:** Norwegian Bokmål.
1194 * **pirate:** American Pirate.
1196 * **pt:** Portuguese.
1197 * **pt_BR:** Brazilian Portuguese.
1201 To submit a new translation for yargs:
1203 1. use `./locales/en.json` as a starting point.
1204 2. submit a pull request with the new locale file.
1206 *The [Microsoft Terminology Search](http://www.microsoft.com/Language/en-US/Search.aspx) can be useful for finding the correct terminology in your locale.*
1208 <a name="nargs"></a>.nargs(key, count)
1211 The number of arguments that should be consumed after a key. This can be a
1212 useful hint to prevent parsing ambiguity. For example:
1215 var argv = require('yargs')
1217 .parse(['--token', '-my-token']);
1222 `{ _: [], token: '-my-token', '$0': 'node test' }`
1224 Optionally `.nargs()` can take an object of `key`/`narg` pairs.
1226 <a name="normalize"></a>.normalize(key)
1229 The key provided represents a path and should have `path.normalize()` applied.
1231 <a name="number"></a>.number(key)
1234 Tell the parser to always interpret `key` as a number.
1236 If `key` is an array, all elements will be parsed as numbers.
1238 If the option is given on the command line without a value, `argv` will be
1239 populated with `undefined`.
1241 If the value given on the command line cannot be parsed as a number, `argv` will
1242 be populated with `NaN`.
1244 Note that decimals, hexadecimals, and scientific notation are all accepted.
1247 var argv = require('yargs')
1249 .number(['width', 'height'])
1258 Instead of chaining together `.alias().demand().default().describe().string()`, you can specify
1259 keys in `opt` for each of the chainable methods.
1264 var argv = require('yargs')
1268 default: '/etc/passwd',
1269 describe: 'x marks the spot',
1279 var argv = require('yargs')
1282 .default('f', '/etc/passwd')
1283 .describe('f', 'x marks the spot')
1289 Optionally `.options()` can take an object that maps keys to `opt` parameters.
1292 var argv = require('yargs')
1297 default: '/etc/passwd',
1298 describe: 'x marks the spot',
1306 Valid `opt` keys include:
1308 - `alias`: string or array of strings, alias(es) for the canonical option key, see [`alias()`](#alias)
1309 - `array`: boolean, interpret option as an array, see [`array()`](#array)
1310 - `boolean`: boolean, interpret option as a boolean flag, see [`boolean()`](#boolean)
1311 - `choices`: value or array of values, limit valid option arguments to a predefined set, see [`choices()`](#choices)
1312 - `config`: boolean, interpret option as a path to a JSON config file, see [`config()`](#config)
1313 - `configParser`: function, provide a custom config parsing function, see [`config()`](#config)
1314 - `count`: boolean, interpret option as a count of boolean flags, see [`count()`](#count)
1315 - `default`: value, set a default value for the option, see [`default()`](#default)
1316 - `defaultDescription`: string, use this description for the default value in help content, see [`default()`](#default)
1317 - `demand`/`require`/`required`: boolean or string, demand the option be given, with optional error message, see [`demand()`](#demand)
1318 - `desc`/`describe`/`description`: string, the option description for help content, see [`describe()`](#describe)
1319 - `global`: boolean, indicate that this key should not be [reset](#reset) when a command is invoked, see [`global()`](#global)
1320 - `group`: string, when displaying usage instructions place the option under an alternative group heading, see [`group()`](#group)
1321 - `nargs`: number, specify how many arguments should be consumed for the option, see [`nargs()`](#nargs)
1322 - `normalize`: boolean, apply `path.normalize()` to the option, see [`normalize()`](#normalize)
1323 - `number`: boolean, interpret option as a number, [`number()`](#number)
1324 - `requiresArg`: boolean, require the option be specified with a value, see [`requiresArg()`](#requiresArg)
1325 - `skipValidation`: boolean, skips validation if the option is present, see [`skipValidation()`](#skipValidation)
1326 - `string`: boolean, interpret option as a string, see [`string()`](#string)
1327 - `type`: one of the following strings
1328 - `'array'`: synonymous for `array: true`, see [`array()`](#array)
1329 - `'boolean'`: synonymous for `boolean: true`, see [`boolean()`](#boolean)
1330 - `'count'`: synonymous for `count: true`, see [`count()`](#count)
1331 - `'number'`: synonymous for `number: true`, see [`number()`](#number)
1332 - `'string'`: synonymous for `string: true`, see [`string()`](#string)
1337 Parse `args` instead of `process.argv`. Returns the `argv` object.
1339 `args` may either be a pre-processed argv array, or a raw argument string.
1341 .pkgConf(key, [cwd])
1344 Similar to [`config()`](#config), indicates that yargs should interpret the object from the specified key in package.json
1345 as a configuration object.
1347 `cwd` can optionally be provided, the package.json will be read
1350 .require(key, [msg | boolean])
1351 ------------------------------
1352 .required(key, [msg | boolean])
1353 ------------------------------
1355 An alias for [`demand()`](#demand). See docs there.
1357 <a name="requiresArg"></a>.requiresArg(key)
1360 Specifies either a single option key (string), or an array of options that
1361 must be followed by option values. If any option value is missing, show the
1362 usage information and exit.
1364 The default behavior is to set the value of any key not followed by an
1365 option value to `true`.
1367 <a name="reset"></a>.reset()
1370 Reset the argument object built up so far. This is useful for
1371 creating nested command line interfaces. Use [global](#global)
1372 to specify keys that should not be reset.
1375 var yargs = require('yargs')
1376 .usage('$0 command')
1377 .command('hello', 'hello command')
1378 .command('world', 'world command')
1379 .demand(1, 'must provide a valid command'),
1381 command = argv._[0];
1383 if (command === 'hello') {
1387 .example('$0 hello', 'print the hello message!')
1390 console.log('hello!');
1391 } else if (command === 'world'){
1395 .example('$0 world', 'print the world message!')
1398 console.log('world!');
1404 .showCompletionScript()
1405 ----------------------
1407 Generate a bash completion script. Users of your application can install this
1408 script in their `.bashrc`, and yargs will provide completion shortcuts for
1409 commands and options.
1411 .showHelp(consoleLevel='error')
1412 ---------------------------
1414 Print the usage data using the [`console`](https://nodejs.org/api/console.html) function `consoleLevel` for printing.
1419 var yargs = require("yargs")
1420 .usage("$0 -operand1 number -operand2 number -operation [add|subtract]");
1421 yargs.showHelp(); //prints to stderr using console.error()
1424 Or, to print the usage data to `stdout` instead, you can specify the use of `console.log`:
1427 yargs.showHelp("log"); //prints to stdout using console.log()
1430 Later on, `argv` can be retrieved with `yargs.argv`.
1432 .showHelpOnFail(enable, [message])
1433 ----------------------------------
1435 By default, yargs outputs a usage string if any error is detected. Use the
1436 `.showHelpOnFail()` method to customize this behavior. If `enable` is `false`,
1437 the usage string is not output. If the `message` parameter is present, this
1438 message is output after the error message.
1444 var argv = require('yargs')
1445 .usage('Count the lines in a file.\nUsage: $0 -f <file>')
1448 .describe('f', 'Load a file')
1450 .showHelpOnFail(false, 'Specify --help for available options')
1460 $ node line_count.js
1461 Missing argument value: f
1463 Specify --help for available options
1466 <a name="skipValidation"></a>.skipValidation(key)
1469 Specifies either a single option key (string), or an array of options.
1470 If any of the options is present, yargs validation is skipped.
1475 Any command-line argument given that is not demanded, or does not have a
1476 corresponding description, will be reported as an error.
1478 <a name="string"></a>.string(key)
1481 Tell the parser logic not to interpret `key` as a number or boolean.
1482 This can be useful if you need to preserve leading zeros in an input.
1484 If `key` is an array, interpret all the elements as strings.
1486 `.string('_')` will result in non-hyphenated arguments being interpreted as strings,
1487 regardless of whether they resemble numbers.
1494 Override the default strings used by yargs with the key/value
1495 pairs provided in `obj`:
1498 var argv = require('yargs')
1499 .command('run', 'the run command')
1502 'Commands:': 'My Commands -->\n'
1516 --help Show help [boolean]
1519 If you explicitly specify a `locale()`, you should do so *before* calling
1522 .usage(message, [opts])
1523 ---------------------
1525 Set a usage message to show which commands to use. Inside `message`, the string
1526 `$0` will get interpolated to the current script name or node command for the
1527 present script similar to how `$0` works in bash or perl.
1529 `opts` is optional and acts like calling `.options(opts)`.
1531 <a name="version"></a>.version([option], [description], [version])
1532 ----------------------------------------
1534 Add an option (e.g. `--version`) that displays the version number (given by the
1535 `version` parameter) and exits the process.
1537 If no arguments are passed to `version` (`.version()`), yargs will parse the `package.json`
1538 of your module and use its `version` value. The default value of `option` is `--version`.
1540 You can provide a `function` for version, rather than a string.
1541 This is useful if you want to use a version stored in a location other than package.json:
1544 var argv = require('yargs')
1545 .version(function() {
1546 return require('../lib/version').version;
1551 <a name="wrap"></a>.wrap(columns)
1554 Format usage output to wrap at `columns` many columns.
1556 By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to
1557 specify no column limit (no right-align). Use `.wrap(yargs.terminalWidth())` to
1558 maximize the width of yargs' usage instructions.
1566 Use `--` to stop parsing flags and stuff the remainder into `argv._`.
1568 $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4
1569 { _: [ '-c', '3', '-d', '4' ],
1572 '$0': 'examples/reflect.js' }
1577 If you want to explicitly set a field to false instead of just leaving it
1578 undefined or to override a default you can do `--no-key`.
1580 $ node examples/reflect.js -a --no-b
1581 { _: [], a: true, b: false, '$0': 'examples/reflect.js' }
1586 Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to
1587 one. This way you can just `net.createConnection(argv.port)` and you can add
1588 numbers out of `argv` with `+` without having that mean concatenation,
1589 which is super frustrating.
1594 If you specify a flag multiple times it will get turned into an array containing
1595 all the values in order.
1597 $ node examples/reflect.js -x 5 -x 8 -x 0
1598 { _: [], x: [ 5, 8, 0 ], '$0': 'examples/reflect.js' }
1603 When you use dots (`.`s) in argument names, an implicit object path is assumed.
1604 This lets you organize arguments into nested objects.
1606 $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5
1608 foo: { bar: { baz: 33 }, quux: 5 },
1609 '$0': 'examples/reflect.js' }
1614 Short numeric `-n5` style arguments work too:
1616 $ node examples/reflect.js -n123 -m456
1617 { _: [], n: 123, m: 456, '$0': 'examples/reflect.js' }
1622 With [npm](https://github.com/npm/npm), just do:
1626 or clone this project on github:
1628 git clone http://github.com/yargs/yargs.git
1630 To run the tests with npm, just do:
1637 Using the `yargs` stanza in your `package.json` you can turn on and off
1638 some of yargs' parsing features:
1643 "short-option-groups": true,
1644 "camel-case-expansion": true,
1645 "dot-notation": true,
1646 "parse-numbers": true,
1647 "boolean-negation": true
1652 See the [yargs-parser](https://github.com/yargs/yargs-parser#configuration) module
1653 for detailed documentation of this feature.
1658 This module is loosely inspired by Perl's
1659 [Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).
1661 [travis-url]: https://travis-ci.org/yargs/yargs
1662 [travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg
1663 [gemnasium-url]: https://gemnasium.com/yargs/yargs
1664 [gemnasium-image]: https://img.shields.io/gemnasium/yargs/yargs.svg
1665 [coveralls-url]: https://coveralls.io/github/yargs/yargs
1666 [coveralls-image]: https://img.shields.io/coveralls/yargs/yargs.svg
1667 [npm-url]: https://www.npmjs.com/package/yargs
1668 [npm-image]: https://img.shields.io/npm/v/yargs.svg
1669 [windows-url]: https://ci.appveyor.com/project/bcoe/yargs-ljwvf
1670 [windows-image]: https://img.shields.io/appveyor/ci/bcoe/yargs-ljwvf/master.svg?label=Windows%20Tests
1671 [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
1672 [standard-url]: http://standardjs.com/
1673 [standard-version-image]: https://img.shields.io/badge/release-standard%20version-brightgreen.svg
1674 [standard-version-url]: https://github.com/conventional-changelog/standard-version