UNPKG

55 kBMarkdownView Raw
1 yargs
2========
3
4Yargs be a node.js library fer hearties tryin' ter parse optstrings.
5
6With yargs, ye be havin' a map that leads straight to yer treasure! Treasure of course, being a simple option hash.
7
8[![Build Status][travis-image]][travis-url]
9[![Coverage Status][coveralls-image]][coveralls-url]
10[![NPM version][npm-image]][npm-url]
11[![Windows Tests][windows-image]][windows-url]
12[![js-standard-style][standard-image]][standard-url]
13[![Conventional Commits][conventional-commits-image]][conventional-commits-url]
14[![Gitter][gitter-image]][gitter-url]
15
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) :)
17
18examples
19========
20
21With yargs, the options be just a hash!
22-------------------------------------------------------------------
23
24plunder.js:
25
26````javascript
27#!/usr/bin/env node
28var argv = require('yargs').argv;
29
30if (argv.ships > 3 && argv.distance < 53.5) {
31 console.log('Plunder more riffiwobbles!');
32} else {
33 console.log('Retreat from the xupptumblers!');
34}
35````
36
37***
38
39 $ ./plunder.js --ships=4 --distance=22
40 Plunder more riffiwobbles!
41
42 $ ./plunder.js --ships 12 --distance 98.7
43 Retreat from the xupptumblers!
44
45![Joe was one optimistic pirate.](https://i.imgur.com/4WFGVJ9.png)
46
47But don't walk the plank just yet! There be more! You can do short options:
48-------------------------------------------------
49
50short.js:
51
52````javascript
53#!/usr/bin/env node
54var argv = require('yargs').argv;
55console.log('(%d,%d)', argv.x, argv.y);
56````
57
58***
59
60 $ ./short.js -x 10 -y 21
61 (10,21)
62
63And booleans, both long, short, and even grouped:
64----------------------------------
65
66bool.js:
67
68````javascript
69#!/usr/bin/env node
70var argv = require('yargs').argv;
71
72if (argv.s) {
73 process.stdout.write(argv.fr ? 'Le perroquet dit: ' : 'The parrot says: ');
74}
75console.log(
76 (argv.fr ? 'couac' : 'squawk') + (argv.p ? '!' : '')
77);
78````
79
80***
81
82 $ ./bool.js -s
83 The parrot says: squawk
84
85 $ ./bool.js -sp
86 The parrot says: squawk!
87
88 $ ./bool.js -sp --fr
89 Le perroquet dit: couac!
90
91And non-hyphenated options too! Just use `argv._`!
92-------------------------------------------------
93
94nonopt.js:
95
96````javascript
97#!/usr/bin/env node
98var argv = require('yargs').argv;
99console.log('(%d,%d)', argv.x, argv.y);
100console.log(argv._);
101````
102
103***
104
105 $ ./nonopt.js -x 6.82 -y 3.35 rum
106 (6.82,3.35)
107 [ 'rum' ]
108
109 $ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho
110 (0.54,1.12)
111 [ 'me hearties', 'yo', 'ho' ]
112
113Yargs even counts your booleans!
114----------------------------------------------------------------------
115
116count.js:
117
118````javascript
119#!/usr/bin/env node
120var argv = require('yargs')
121 .count('verbose')
122 .alias('v', 'verbose')
123 .argv;
124
125VERBOSE_LEVEL = argv.verbose;
126
127function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); }
128function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); }
129function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); }
130
131WARN("Showing only important stuff");
132INFO("Showing semi-important stuff too");
133DEBUG("Extra chatty mode");
134````
135
136***
137 $ node count.js
138 Showing only important stuff
139
140 $ node count.js -v
141 Showing only important stuff
142 Showing semi-important stuff too
143
144 $ node count.js -vv
145 Showing only important stuff
146 Showing semi-important stuff too
147 Extra chatty mode
148
149 $ node count.js -v --verbose
150 Showing only important stuff
151 Showing semi-important stuff too
152 Extra chatty mode
153
154Tell users how to use yer options and make demands.
155-------------------------------------------------
156
157area.js:
158
159````javascript
160#!/usr/bin/env node
161var argv = require('yargs')
162 .usage('Usage: $0 -w [num] -h [num]')
163 .demandOption(['w','h'])
164 .argv;
165
166console.log("The area is:", argv.w * argv.h);
167````
168
169***
170
171 $ ./area.js -w 55 -h 11
172 The area is: 605
173
174 $ node ./area.js -w 4.91 -w 2.51
175 Usage: area.js -w [num] -h [num]
176
177 Options:
178 -w [required]
179 -h [required]
180
181 Missing required arguments: h
182
183After yer demands have been met, demand more! Ask for non-hyphenated arguments!
184-----------------------------------------
185
186demand_count.js:
187
188````javascript
189#!/usr/bin/env node
190var argv = require('yargs')
191 .demandCommand(2)
192 .argv;
193console.dir(argv);
194````
195
196***
197
198 $ ./demand_count.js a
199
200 Not enough non-option arguments: got 1, need at least 2
201
202 $ ./demand_count.js a b
203 { _: [ 'a', 'b' ], '$0': 'demand_count.js' }
204
205 $ ./demand_count.js a b c
206 { _: [ 'a', 'b', 'c' ], '$0': 'demand_count.js' }
207
208EVEN MORE SHIVER ME TIMBERS!
209------------------
210
211default_singles.js:
212
213````javascript
214#!/usr/bin/env node
215var argv = require('yargs')
216 .default('x', 10)
217 .default('y', 10)
218 .argv
219;
220console.log(argv.x + argv.y);
221````
222
223***
224
225 $ ./default_singles.js -x 5
226 15
227
228default_hash.js:
229
230````javascript
231#!/usr/bin/env node
232var argv = require('yargs')
233 .default({ x : 10, y : 10 })
234 .argv
235;
236console.log(argv.x + argv.y);
237````
238
239***
240
241 $ ./default_hash.js -y 7
242 17
243
244And if you really want to get all descriptive about it...
245---------------------------------------------------------
246
247boolean_single.js:
248
249````javascript
250#!/usr/bin/env node
251var argv = require('yargs')
252 .boolean('v')
253 .argv
254;
255console.dir(argv.v);
256console.dir(argv._);
257````
258
259***
260
261 $ ./boolean_single.js -v "me hearties" yo ho
262 true
263 [ 'me hearties', 'yo', 'ho' ]
264
265
266boolean_double.js:
267
268````javascript
269#!/usr/bin/env node
270var argv = require('yargs')
271 .boolean(['x','y','z'])
272 .argv
273;
274console.dir([ argv.x, argv.y, argv.z ]);
275console.dir(argv._);
276````
277
278***
279
280 $ ./boolean_double.js -x -z one two three
281 [ true, false, true ]
282 [ 'one', 'two', 'three' ]
283
284Yargs is here to help you...
285---------------------------
286
287Ye can describe parameters fer help messages and set aliases. Yargs figures
288out how ter format a handy help string automatically.
289
290line_count.js:
291
292````javascript
293#!/usr/bin/env node
294var argv = require('yargs')
295 .usage('Usage: $0 <command> [options]')
296 .command('count', 'Count the lines in a file')
297 .example('$0 count -f foo.js', 'count the lines in the given file')
298 .alias('f', 'file')
299 .nargs('f', 1)
300 .describe('f', 'Load a file')
301 .demandOption(['f'])
302 .help('h')
303 .alias('h', 'help')
304 .epilog('copyright 2015')
305 .argv;
306
307var fs = require('fs');
308var s = fs.createReadStream(argv.file);
309
310var lines = 0;
311s.on('data', function (buf) {
312 lines += buf.toString().match(/\n/g).length;
313});
314
315s.on('end', function () {
316 console.log(lines);
317});
318````
319
320***
321 $ node line_count.js count
322 Usage: line_count.js <command> [options]
323
324 Commands:
325 count Count the lines in a file
326
327 Options:
328 -f, --file Load a file [required]
329 -h, --help Show help [boolean]
330
331 Examples:
332 line_count.js count -f foo.js count the lines in the given file
333
334 copyright 2015
335
336 Missing required arguments: f
337
338 $ node line_count.js count --file line_count.js
339 26
340
341 $ node line_count.js count -f line_count.js
342 26
343
344methods
345=======
346
347By itself,
348
349````javascript
350require('yargs').argv
351````
352
353will use the `process.argv` array to construct the `argv` object.
354
355You can pass in the `process.argv` yourself:
356
357````javascript
358require('yargs')([ '-x', '1', '-y', '2' ]).argv
359````
360
361or use `.parse()` to do the same thing:
362
363````javascript
364require('yargs').parse([ '-x', '1', '-y', '2' ])
365````
366
367The rest of these methods below come in just before the terminating `.argv`.
368
369<a name="alias"></a>.alias(key, alias)
370------------------
371
372Set key names as equivalent such that updates to a key will propagate to aliases
373and vice-versa.
374
375Optionally `.alias()` can take an object that maps keys to aliases.
376Each key of this object should be the canonical version of the option, and each
377value should be a string or an array of strings.
378
379.argv
380-----
381
382Get the arguments as a plain old object.
383
384Arguments without a corresponding flag show up in the `argv._` array.
385
386The script name or node command is available at `argv.$0` similarly to how `$0`
387works in bash or perl.
388
389If `yargs` is executed in an environment that embeds node and there's no script name (e.g.
390[Electron](http://electron.atom.io/) or [nw.js](http://nwjs.io/)), it will ignore the first parameter since it
391expects it to be the script name. In order to override this behavior, use `.parse(process.argv.slice(1))`
392instead of `.argv` and the first parameter won't be ignored.
393
394<a name="array"></a>.array(key)
395----------
396
397Tell the parser to interpret `key` as an array. If `.array('foo')` is set,
398`--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`.
399
400<a name="boolean"></a>.boolean(key)
401-------------
402
403Interpret `key` as a boolean. If a non-flag option follows `key` in
404`process.argv`, that string won't get set as the value of `key`.
405
406`key` will default to `false`, unless a `default(key, undefined)` is
407explicitly set.
408
409If `key` is an array, interpret all the elements as booleans.
410
411.check(fn, [global=true])
412----------
413
414Check that certain conditions are met in the provided arguments.
415
416`fn` is called with two arguments, the parsed `argv` hash and an array of options and their aliases.
417
418If `fn` throws or returns a non-truthy value, show the thrown error, usage information, and
419exit.
420
421`global` indicates whether `check()` should be enabled both
422at the top-level and for each sub-command.
423
424<a name="choices"></a>.choices(key, choices)
425----------------------
426
427Limit valid values for `key` to a predefined set of `choices`, given as an array
428or as an individual value.
429
430```js
431var argv = require('yargs')
432 .alias('i', 'ingredient')
433 .describe('i', 'choose your sandwich ingredients')
434 .choices('i', ['peanut-butter', 'jelly', 'banana', 'pickles'])
435 .help('help')
436 .argv
437```
438
439If this method is called multiple times, all enumerated values will be merged
440together. Choices are generally strings or numbers, and value matching is
441case-sensitive.
442
443Optionally `.choices()` can take an object that maps multiple keys to their
444choices.
445
446Choices can also be specified as `choices` in the object given to `option()`.
447
448```js
449var argv = require('yargs')
450 .option('size', {
451 alias: 's',
452 describe: 'choose a size',
453 choices: ['xs', 's', 'm', 'l', 'xl']
454 })
455 .argv
456```
457
458<a name="coerce"></a>.coerce(key, fn)
459----------------
460
461Provide a synchronous function to coerce or transform the value(s) given on the
462command line for `key`.
463
464The coercion function should accept one argument, representing the parsed value
465from the command line, and should return a new value or throw an error. The
466returned value will be used as the value for `key` (or one of its aliases) in
467`argv`.
468
469If the function throws, the error will be treated as a validation
470failure, delegating to either a custom [`.fail()`](#fail) handler or printing
471the error message in the console.
472
473Coercion will be applied to a value after
474all other modifications, such as [`.normalize()`](#normalize).
475
476_Examples:_
477
478```js
479var argv = require('yargs')
480 .coerce('file', function (arg) {
481 return require('fs').readFileSync(arg, 'utf8')
482 })
483 .argv
484```
485
486Optionally `.coerce()` can take an object that maps several keys to their
487respective coercion function.
488
489```js
490var argv = require('yargs')
491 .coerce({
492 date: Date.parse,
493 json: JSON.parse
494 })
495 .argv
496```
497
498You can also map the same function to several keys at one time. Just pass an
499array of keys as the first argument to `.coerce()`:
500
501```js
502var path = require('path')
503var argv = require('yargs')
504 .coerce(['src', 'dest'], path.resolve)
505 .argv
506```
507
508If you are using dot-notion or arrays, .e.g., `user.email` and `user.password`,
509coercion will be applied to the final object that has been parsed:
510
511```js
512// --user.name Batman --user.password 123
513// gives us: {name: 'batman', password: '[SECRET]'}
514var argv = require('yargs')
515 .option('user')
516 .coerce('user', opt => {
517 opt.name = opt.name.toLowerCase()
518 opt.password = '[SECRET]'
519 return opt
520 })
521 .argv
522```
523
524.command(cmd, desc, [builder], [handler])
525-----------------------------------------
526.command(cmd, desc, [module])
527-----------------------------
528.command(module)
529----------------
530
531Define the commands exposed by your application.
532
533`cmd` should be a string representing the command or an array of strings
534representing the command and its aliases. Read more about command aliases in the
535subsection below.
536
537Use `desc` to provide a description for each command your application accepts (the
538values stored in `argv._`). Set `desc` to `false` to create a hidden command.
539Hidden commands don't show up in the help output and aren't available for
540completion.
541
542Optionally, you can provide a `builder` object to give hints about the
543options that your command accepts:
544
545```js
546yargs
547 .command('get', 'make a get HTTP request', {
548 url: {
549 alias: 'u',
550 default: 'http://yargs.js.org/'
551 }
552 })
553 .help()
554 .argv
555```
556
557`builder` can also be a function. This function is executed
558with a `yargs` instance, and can be used to provide _advanced_ command specific help:
559
560```js
561yargs
562 .command('get', 'make a get HTTP request', function (yargs) {
563 return yargs.option('url', {
564 alias: 'u',
565 default: 'http://yargs.js.org/'
566 })
567 })
568 .help()
569 .argv
570```
571
572You can also provide a handler function, which will be executed with the
573parsed `argv` object:
574
575```js
576yargs
577 .command(
578 'get',
579 'make a get HTTP request',
580 function (yargs) {
581 return yargs.option('u', {
582 alias: 'url',
583 describe: 'the URL to make an HTTP request to'
584 })
585 },
586 function (argv) {
587 console.log(argv.url)
588 }
589 )
590 .help()
591 .argv
592```
593
594### Default Commands
595
596To specify a default command use the character `*`. A default command
597will be run if the positional arguments provided match no known
598commands:
599
600```js
601const argv = require('yargs')
602 .command('*', 'the default command', () => {}, (argv) => {
603 console.log('this command will be run by default')
604 })
605```
606
607The command defined above will be executed if the program
608is run with `./my-cli.js --x=22`.
609
610Default commands can also be used as a command alias, like so:
611
612```js
613const argv = require('yargs')
614 .command(['serve', '*'], 'the serve command', () => {}, (argv) => {
615 console.log('this command will be run by default')
616 })
617```
618
619The command defined above will be executed if the program
620is run with `./my-cli.js --x=22`, or with `./my-cli.js serve --x=22`.
621
622### Positional Arguments
623
624Commands can accept _optional_ and _required_ positional arguments. Required
625positional arguments take the form `<foo>`, and optional arguments
626take the form `[bar]`. The parsed positional arguments will be populated in
627`argv`:
628
629```js
630yargs.command('get <source> [proxy]', 'make a get HTTP request')
631 .help()
632 .argv
633```
634
635#### Positional Argument Aliases
636
637Aliases can be provided for positional arguments using the `|` character.
638As an example, suppose our application allows either a username _or_
639an email as the first argument:
640
641```js
642yargs.command('get <username|email> [password]', 'fetch a user by username or email.')
643 .help()
644 .argv
645```
646
647In this way, both `argv.username` and `argv.email` would be populated with the
648same value when the command is executed.
649
650#### Variadic Positional Arguments
651
652The last positional argument can optionally accept an array of
653values, by using the `..` operator:
654
655```js
656yargs.command('download <url> [files..]', 'download several files')
657 .help()
658 .argv
659```
660
661### Command Execution
662
663When a command is given on the command line, yargs will execute the following:
664
6651. push the command into the current context
6662. reset non-global configuration
6673. apply command configuration via the `builder`, if given
6684. parse and validate args from the command line, including positional args
6695. if validation succeeds, run the `handler` function, if given
6706. pop the command from the current context
671
672### Command Aliases
673
674You can define aliases for a command by putting the command and all of its
675aliases into an array.
676
677Alternatively, a command module may specify an `aliases` property, which may be
678a string or an array of strings. All aliases defined via the `command` property
679and the `aliases` property will be concatenated together.
680
681The first element in the array is considered the canonical command, which may
682define positional arguments, and the remaining elements in the array are
683considered aliases. Aliases inherit positional args from the canonical command,
684and thus any positional args defined in the aliases themselves are ignored.
685
686If either the canonical command or any of its aliases are given on the command
687line, the command will be executed.
688
689```js
690#!/usr/bin/env node
691require('yargs')
692 .command(['start [app]', 'run', 'up'], 'Start up an app', {}, (argv) => {
693 console.log('starting up the', argv.app || 'default', 'app')
694 })
695 .command({
696 command: 'configure <key> [value]',
697 aliases: ['config', 'cfg'],
698 desc: 'Set a config variable',
699 builder: (yargs) => yargs.default('value', 'true'),
700 handler: (argv) => {
701 console.log(`setting ${argv.key} to ${argv.value}`)
702 }
703 })
704 .demandCommand()
705 .help()
706 .wrap(72)
707 .argv
708```
709
710```
711$ ./svc.js help
712Commands:
713 start [app] Start up an app [aliases: run, up]
714 configure <key> [value] Set a config variable [aliases: config, cfg]
715
716Options:
717 --help Show help [boolean]
718
719$ ./svc.js cfg concurrency 4
720setting concurrency to 4
721
722$ ./svc.js run web
723starting up the web app
724```
725
726### Providing a Command Module
727
728For complicated commands you can pull the logic into a module. A module
729simply needs to export:
730
731* `exports.command`: string (or array of strings) that executes this command when given on the command line, first string may contain positional args
732* `exports.aliases`: array of strings (or a single string) representing aliases of `exports.command`, positional args defined in an alias are ignored
733* `exports.describe`: string used as the description for the command in help text, use `false` for a hidden command
734* `exports.builder`: object declaring the options the command accepts, or a function accepting and returning a yargs instance
735* `exports.handler`: a function which will be passed the parsed argv.
736
737```js
738// my-module.js
739exports.command = 'get <source> [proxy]'
740
741exports.describe = 'make a get HTTP request'
742
743exports.builder = {
744 banana: {
745 default: 'cool'
746 },
747 batman: {
748 default: 'sad'
749 }
750}
751
752exports.handler = function (argv) {
753 // do something with argv.
754}
755```
756
757You then register the module like so:
758
759```js
760yargs.command(require('my-module'))
761 .help()
762 .argv
763```
764
765Or if the module does not export `command` and `describe` (or if you just want to override them):
766
767```js
768yargs.command('get <source> [proxy]', 'make a get HTTP request', require('my-module'))
769 .help()
770 .argv
771```
772
773.commandDir(directory, [opts])
774------------------------------
775
776Apply command modules from a directory relative to the module calling this method.
777
778This allows you to organize multiple commands into their own modules under a
779single directory and apply all of them at once instead of calling
780`.command(require('./dir/module'))` multiple times.
781
782By default, it ignores subdirectories. This is so you can use a directory
783structure to represent your command hierarchy, where each command applies its
784subcommands using this method in its builder function. See the example below.
785
786Note that yargs assumes all modules in the given directory are command modules
787and will error if non-command modules are encountered. In this scenario, you
788can either move your module to a different directory or use the `exclude` or
789`visit` option to manually filter it out. More on that below.
790
791`directory` is a relative directory path as a string (required).
792
793`opts` is an options object (optional). The following options are valid:
794
795- `recurse`: boolean, default `false`
796
797 Look for command modules in all subdirectories and apply them as a flattened
798 (non-hierarchical) list.
799
800- `extensions`: array of strings, default `['js']`
801
802 The types of files to look for when requiring command modules.
803
804- `visit`: function
805
806 A synchronous function called for each command module encountered. Accepts
807 `commandObject`, `pathToFile`, and `filename` as arguments. Returns
808 `commandObject` to include the command; any falsy value to exclude/skip it.
809
810- `include`: RegExp or function
811
812 Whitelist certain modules. See [`require-directory` whitelisting](https://www.npmjs.com/package/require-directory#whitelisting) for details.
813
814- `exclude`: RegExp or function
815
816 Blacklist certain modules. See [`require-directory` blacklisting](https://www.npmjs.com/package/require-directory#blacklisting) for details.
817
818### Example command hierarchy using `.commandDir()`
819
820Desired CLI:
821
822```sh
823$ myapp --help
824$ myapp init
825$ myapp remote --help
826$ myapp remote add base http://yargs.js.org
827$ myapp remote prune base
828$ myapp remote prune base fork whatever
829```
830
831Directory structure:
832
833```
834myapp/
835├─ cli.js
836└─ cmds/
837 ├─ init.js
838 ├─ remote.js
839 └─ remote_cmds/
840 ├─ add.js
841 └─ prune.js
842```
843
844cli.js:
845
846```js
847#!/usr/bin/env node
848require('yargs')
849 .commandDir('cmds')
850 .demandCommand()
851 .help()
852 .argv
853```
854
855cmds/init.js:
856
857```js
858exports.command = 'init [dir]'
859exports.desc = 'Create an empty repo'
860exports.builder = {
861 dir: {
862 default: '.'
863 }
864}
865exports.handler = function (argv) {
866 console.log('init called for dir', argv.dir)
867}
868```
869
870cmds/remote.js:
871
872```js
873exports.command = 'remote <command>'
874exports.desc = 'Manage set of tracked repos'
875exports.builder = function (yargs) {
876 return yargs.commandDir('remote_cmds')
877}
878exports.handler = function (argv) {}
879```
880
881cmds/remote_cmds/add.js:
882
883```js
884exports.command = 'add <name> <url>'
885exports.desc = 'Add remote named <name> for repo at url <url>'
886exports.builder = {}
887exports.handler = function (argv) {
888 console.log('adding remote %s at url %s', argv.name, argv.url)
889}
890```
891
892cmds/remote_cmds/prune.js:
893
894```js
895exports.command = 'prune <name> [names..]'
896exports.desc = 'Delete tracked branches gone stale for remotes'
897exports.builder = {}
898exports.handler = function (argv) {
899 console.log('pruning remotes %s', [].concat(argv.name).concat(argv.names).join(', '))
900}
901```
902
903.completion([cmd], [description], [fn])
904---------------------------------------
905
906Enable bash-completion shortcuts for commands and options.
907
908`cmd`: When present in `argv._`, will result in the `.bashrc` completion script
909being outputted. To enable bash completions, concat the generated script to your
910`.bashrc` or `.bash_profile`.
911
912`description`: Provide a description in your usage instructions for the command
913that generates bash completion scripts.
914
915`fn`: Rather than relying on yargs' default completion functionality, which
916shiver me timbers is pretty awesome, you can provide your own completion
917method.
918
919If invoked without parameters, `.completion()` will make `completion` the command to output
920the completion script.
921
922```js
923var argv = require('yargs')
924 .completion('completion', function(current, argv) {
925 // 'current' is the current command being completed.
926 // 'argv' is the parsed arguments so far.
927 // simply return an array of completions.
928 return [
929 'foo',
930 'bar'
931 ];
932 })
933 .argv;
934```
935
936You can also provide asynchronous completions.
937
938```js
939var argv = require('yargs')
940 .completion('completion', function(current, argv, done) {
941 setTimeout(function() {
942 done([
943 'apple',
944 'banana'
945 ]);
946 }, 500);
947 })
948 .argv;
949```
950
951But wait, there's more! You can return an asynchronous promise.
952
953```js
954var argv = require('yargs')
955 .completion('completion', function(current, argv, done) {
956 return new Promise(function (resolve, reject) {
957 setTimeout(function () {
958 resolve(['apple', 'banana'])
959 }, 10)
960 })
961 })
962 .argv;
963```
964
965<a name="config"></a>.config([key], [description], [parseFn])
966-------------------------------------------------------------
967.config(object)
968---------------
969
970Tells the parser that if the option specified by `key` is passed in, it
971should be interpreted as a path to a JSON config file. The file is loaded
972and parsed, and its properties are set as arguments. Because the file is
973loaded using Node's require(), the filename MUST end in `.json` to be
974interpreted correctly.
975
976If invoked without parameters, `.config()` will make `--config` the option to pass the JSON config file.
977
978An optional `description` can be provided to customize the config (`key`) option
979in the usage string.
980
981An optional `parseFn` can be used to provide a custom parser. The parsing
982function must be synchronous, and should return an object containing
983key value pairs or an error.
984
985```js
986var argv = require('yargs')
987 .config('settings', function (configPath) {
988 return JSON.parse(fs.readFileSync(configPath, 'utf-8'))
989 })
990 .argv
991```
992
993You can also pass an explicit configuration `object`, it will be parsed
994and its properties will be set as arguments.
995
996```js
997var argv = require('yargs')
998 .config({foo: 1, bar: 2})
999 .argv
1000console.log(argv)
1001```
1002
1003```
1004$ node test.js
1005{ _: [],
1006 foo: 1,
1007 bar: 2,
1008 '$0': 'test.js' }
1009```
1010
1011### `extends` Keyword
1012
1013`config` and `pkgConf` can provide the `extends` keyword to
1014indicate that configuration should inherit from another location.
1015
1016The value of extends can be either a relative or absolute path to a JSON
1017configuration file, e.g.,
1018
1019```js
1020yargs.config({
1021 extends: './configs/a.json',
1022 logLevel: 'verbose'
1023})
1024```
1025
1026Or, a module can be provided (this is useful for creating functionality like
1027 [babel-presets](https://babeljs.io/docs/plugins/)).
1028
1029**my-library.js**
1030
1031```js
1032yargs.pkgConf('nyc')
1033```
1034
1035**consuming package.json**
1036
1037```json
1038{
1039 "nyc": {
1040 "extends": "nyc-babel-config"
1041 }
1042}
1043```
1044
1045Where `nyc-babel-config` is a package that exports configuration in its index.
1046
1047<a name="conflicts"></a>.conflicts(x, y)
1048----------------------------------------------
1049
1050Given the key `x` is set, the key `y` must not be set.
1051
1052Optionally `.conflicts()` can accept an object specifying multiple conflicting keys.
1053
1054<a name="count"></a>.count(key)
1055------------
1056
1057Interpret `key` as a boolean flag, but set its parsed value to the number of
1058flag occurrences rather than `true` or `false`. Default value is thus `0`.
1059
1060<a name="default"></a>.default(key, value, [description])
1061---------------------------------------------------------
1062.defaults(key, value, [description])
1063------------------------------------
1064
1065**Note:** The `.defaults()` alias is deprecated. It will be
1066removed in the next major version.
1067
1068Set `argv[key]` to `value` if no option was specified in `process.argv`.
1069
1070Optionally `.default()` can take an object that maps keys to default values.
1071
1072But wait, there's more! The default value can be a `function` which returns
1073a value. The name of the function will be used in the usage string:
1074
1075```js
1076var argv = require('yargs')
1077 .default('random', function randomValue() {
1078 return Math.random() * 256;
1079 }).argv;
1080```
1081
1082Optionally, `description` can also be provided and will take precedence over
1083displaying the value in the usage instructions:
1084
1085```js
1086.default('timeout', 60000, '(one-minute)')
1087```
1088
1089<a name="demand"></a>.demand(count, [max], [msg]) [DEPRECATED]
1090--------------------
1091
1092`demand()` has been deprecated, please instead see [`demandOption()`](#demandOption) and
1093[`demandCommand()`](#demandCommand).
1094
1095<a name="demandOption"></a>.demandOption(key, [msg | boolean])
1096------------------------------
1097.demandOption(key, msg)
1098------------------------------
1099
1100If `key` is a string, show the usage information and exit if `key` wasn't
1101specified in `process.argv`.
1102
1103If `key` is an array, demand each element.
1104
1105If a `msg` string is given, it will be printed when the argument is missing, instead of the standard error message.
1106
1107```javascript
1108// demand an array of keys to be provided
1109require('yargs')
1110 .option('run', {
1111 alias: 'r',
1112 describe: 'run your program'
1113 })
1114 .option('path', {
1115 alias: 'p',
1116 describe: 'provide a path to file'
1117 })
1118 .option('spec', {
1119 alias: 's',
1120 describe: 'program specifications'
1121 })
1122 .demandOption(['run', 'path'], 'Please provide both run and path arguments to work with this tool')
1123 .help()
1124 .argv
1125```
1126which will provide the following output:
1127```bash
1128Options:
1129 --run, -r run your program [required]
1130 --path, -p provide a path to file [required]
1131 --spec, -s program specifications
1132 --help Show help [boolean]
1133
1134 Missing required arguments: run, path
1135 Please provide both run and path arguments to work with this tool
1136```
1137
1138If a `boolean` value is given, it controls whether the option is demanded;
1139this is useful when using `.options()` to specify command line parameters.
1140
1141```javascript
1142// demand individual options within the option constructor
1143require('yargs')
1144 .options({
1145 'run': {
1146 alias: 'r',
1147 describe: 'run your program',
1148 demandOption: true
1149 },
1150 'path': {
1151 alias: 'p',
1152 describe: 'provide a path to file',
1153 demandOption: true
1154 },
1155 'spec': {
1156 alias: 's',
1157 describe: 'program specifications'
1158 }
1159 })
1160 .help()
1161 .argv
1162```
1163which will provide the following output:
1164```bash
1165Options:
1166 --run, -r run your program [required]
1167 --path, -p provide a path to file [required]
1168 --spec, -s program specifications
1169 --help Show help [boolean]
1170
1171Missing required arguments: run, path
1172```
1173
1174<a name="demandCommand"></a>.demandCommand([min=1], [minMsg])
1175------------------------------
1176.demandCommand([min=1], [max], [minMsg], [maxMsg])
1177------------------------------
1178
1179Demand in context of commands. You can demand a minimum and a maximum number a user can have within your program, as well as provide corresponding error messages if either of the demands is not met.
1180```javascript
1181require('yargs')
1182 .command({
1183 command: 'configure <key> [value]',
1184 aliases: ['config', 'cfg'],
1185 desc: 'Set a config variable',
1186 builder: (yargs) => yargs.default('value', 'true'),
1187 handler: (argv) => {
1188 console.log(`setting ${argv.key} to ${argv.value}`)
1189 }
1190 })
1191 // provide a minimum demand and a minimum demand message
1192 .demandCommand(1, 'You need at least one command before moving on')
1193 .help()
1194 .argv
1195```
1196
1197which will provide the following output:
1198
1199```bash
1200Commands:
1201 configure <key> [value] Set a config variable [aliases: config, cfg]
1202
1203Options:
1204 --help Show help [boolean]
1205
1206You need at least one command before moving on
1207```
1208
1209_Note: in `minMsg` and `maxMsg`, every occurrence of `$0` will be replaced
1210with the observed value, and every instance of `$1` will be replaced with the
1211expected value._
1212
1213<a name="describe"></a>.describe(key, desc)
1214--------------------
1215
1216Describe a `key` for the generated usage information.
1217
1218Optionally `.describe()` can take an object that maps keys to descriptions.
1219
1220.detectLocale(boolean)
1221-----------
1222
1223Should yargs attempt to detect the os' locale? Defaults to `true`.
1224
1225.env([prefix])
1226--------------
1227
1228Tell yargs to parse environment variables matching the given prefix and apply
1229them to argv as though they were command line arguments.
1230
1231Use the "__" separator in the environment variable to indicate nested options.
1232(e.g. prefix_nested__foo => nested.foo)
1233
1234If this method is called with no argument or with an empty string or with `true`,
1235then all env vars will be applied to argv.
1236
1237Program arguments are defined in this order of precedence:
1238
12391. Command line args
12402. Env vars
12413. Config file/objects
12424. Configured defaults
1243
1244```js
1245var argv = require('yargs')
1246 .env('MY_PROGRAM')
1247 .option('f', {
1248 alias: 'fruit-thing',
1249 default: 'apple'
1250 })
1251 .argv
1252console.log(argv)
1253```
1254
1255```
1256$ node fruity.js
1257{ _: [],
1258 f: 'apple',
1259 'fruit-thing': 'apple',
1260 fruitThing: 'apple',
1261 '$0': 'fruity.js' }
1262```
1263
1264```
1265$ MY_PROGRAM_FRUIT_THING=banana node fruity.js
1266{ _: [],
1267 fruitThing: 'banana',
1268 f: 'banana',
1269 'fruit-thing': 'banana',
1270 '$0': 'fruity.js' }
1271```
1272
1273```
1274$ MY_PROGRAM_FRUIT_THING=banana node fruity.js -f cat
1275{ _: [],
1276 f: 'cat',
1277 'fruit-thing': 'cat',
1278 fruitThing: 'cat',
1279 '$0': 'fruity.js' }
1280```
1281
1282Env var parsing is disabled by default, but you can also explicitly disable it
1283by calling `.env(false)`, e.g. if you need to undo previous configuration.
1284
1285.epilog(str)
1286------------
1287.epilogue(str)
1288--------------
1289
1290A message to print at the end of the usage instructions, e.g.
1291
1292```js
1293var argv = require('yargs')
1294 .epilogue('for more information, find our manual at http://example.com');
1295```
1296
1297.example(cmd, desc)
1298-------------------
1299
1300Give some example invocations of your program. Inside `cmd`, the string
1301`$0` will get interpolated to the current script name or node command for the
1302present script similar to how `$0` works in bash or perl.
1303Examples will be printed out as part of the help message.
1304
1305<a name="exitprocess"></a>.exitProcess(enable)
1306----------------------------------
1307
1308By default, yargs exits the process when the user passes a help flag, uses the
1309`.version` functionality, or when validation fails. Calling
1310`.exitProcess(false)` disables this behavior, enabling further actions after
1311yargs have been validated.
1312
1313<a name="fail"></a>.fail(fn)
1314---------
1315
1316Method to execute when a failure occurs, rather than printing the failure message.
1317
1318`fn` is called with the failure message that would have been printed, the
1319`Error` instance originally thrown and yargs state when the failure
1320occured.
1321
1322```js
1323var argv = require('yargs')
1324 .fail(function (msg, err, yargs) {
1325 if (err) throw err // preserve stack
1326 console.error('You broke it!')
1327 console.error(msg)
1328 console.error('You should be doing', yargs.help())
1329 process.exit(1)
1330 })
1331 .argv
1332```
1333
1334.getCompletion(args, done);
1335---------------------------
1336
1337Allows to programmatically get completion choices for any line.
1338
1339`args`: An array of the words in the command line to complete.
1340
1341`done`: The callback to be called with the resulting completions.
1342
1343For example:
1344
1345```js
1346require('yargs')
1347 .option('foobar')
1348 .option('foobaz')
1349 .completion()
1350 .getCompletion(['./test.js', '--foo'], function (completions) {
1351 console.log(completions)
1352 })
1353```
1354
1355Outputs the same completion choices as `./test.js --foo`<kbd>TAB</kbd>: `--foobar` and `--foobaz`
1356
1357<a name="global"></a>.global(globals, [global=true])
1358------------
1359
1360Indicate that an option (or group of options) should not be reset when a command
1361is executed, as an example:
1362
1363```js
1364var argv = require('yargs')
1365 .option('a', {
1366 alias: 'all',
1367 default: true,
1368 global: false
1369 })
1370 .option('n', {
1371 alias: 'none',
1372 default: true,
1373 global: false
1374 })
1375 .command('foo', 'foo command', function (yargs) {
1376 return yargs.option('b', {
1377 alias: 'bar'
1378 })
1379 })
1380 .help('help')
1381 .global('a')
1382 .argv
1383```
1384
1385If the `foo` command is executed the `all` option will remain, but the `none`
1386option will have been eliminated.
1387
1388Options default to being global.
1389
1390<a name="group"></a>.group(key(s), groupName)
1391--------------------
1392
1393Given a key, or an array of keys, places options under an alternative heading
1394when displaying usage instructions, e.g.,
1395
1396```js
1397var yargs = require('yargs')(['--help'])
1398 .help()
1399 .group('batman', 'Heroes:')
1400 .describe('batman', "world's greatest detective")
1401 .wrap(null)
1402 .argv
1403```
1404***
1405 Heroes:
1406 --batman world's greatest detective
1407
1408 Options:
1409 --help Show help [boolean]
1410
1411<a name="help"></a>.help()
1412-----------------------------------------
1413.help([option | boolean])
1414-----------------------------------------
1415.help([option, [description | boolean]])
1416-----------------------------------------
1417.help([option, [description, [boolean]]])
1418-----------------------------------------
1419
1420Add an option (e.g. `--help`) and implicit command that displays the usage
1421string and exits the process.
1422
1423If present, the `description` parameter customizes the description of
1424the help option in the usage string.
1425
1426If a boolean argument is provided, it will enable or disable the use of an
1427implicit command. The implicit command is enabled by default, but it can be
1428disabled by passing `false`.
1429
1430Note that any multi-char aliases (e.g. `help`) used for the help option will
1431also be used for the implicit command. If there are no multi-char aliases (e.g.
1432`h`), then all single-char aliases will be used for the command.
1433
1434If invoked without parameters, `.help()` will use `--help` as the option and
1435`help` as the implicit command to trigger help output.
1436
1437Example:
1438
1439```js
1440var yargs = require("yargs")(['--help'])
1441 .usage("$0 -operand1 number -operand2 number -operation [add|subtract]")
1442 .help()
1443 .argv
1444```
1445
1446Later on, `argv` can be retrieved with `yargs.argv`.
1447
1448<a name="implies"></a>.implies(x, y)
1449--------------
1450
1451Given the key `x` is set, it is required that the key `y` is set.
1452
1453Optionally `.implies()` can accept an object specifying multiple implications.
1454
1455.locale()
1456---------
1457
1458Return the locale that yargs is currently using.
1459
1460By default, yargs will auto-detect the operating system's locale so that
1461yargs-generated help content will display in the user's language.
1462
1463To override this behavior with a static locale, pass the desired locale as a
1464string to this method (see below).
1465
1466.locale(locale)
1467---------------
1468
1469Override the auto-detected locale from the user's operating system with a static
1470locale. Note that the OS locale can be modified by setting/exporting the `LC_ALL`
1471environment variable.
1472
1473```js
1474var argv = require('yargs')
1475 .usage('./$0 - follow ye instructions true')
1476 .option('option', {
1477 alias: 'o',
1478 describe: "'tis a mighty fine option",
1479 demandOption: true
1480 })
1481 .command('run', "Arrr, ya best be knowin' what yer doin'")
1482 .example('$0 run foo', "shiver me timbers, here's an example for ye")
1483 .help('help')
1484 .wrap(70)
1485 .locale('pirate')
1486 .argv
1487```
1488
1489***
1490
1491```shell
1492./test.js - follow ye instructions true
1493
1494Choose yer command:
1495 run Arrr, ya best be knowin' what yer doin'
1496
1497Options for me hearties!
1498 --option, -o 'tis a mighty fine option [requi-yar-ed]
1499 --help Parlay this here code of conduct [boolean]
1500
1501Ex. marks the spot:
1502 test.js run foo shiver me timbers, here's an example for ye
1503
1504Ye be havin' to set the followin' argument land lubber: option
1505```
1506
1507Locales currently supported:
1508
1509* **de:** German.
1510* **en:** American English.
1511* **es:** Spanish.
1512* **fr:** French.
1513* **hi:** Hindi.
1514* **hu:** Hungarian.
1515* **id:** Indonesian.
1516* **it:** Italian.
1517* **ja:** Japanese.
1518* **ko:** Korean.
1519* **nb:** Norwegian Bokmål.
1520* **pirate:** American Pirate.
1521* **pl:** Polish.
1522* **pt:** Portuguese.
1523* **pt_BR:** Brazilian Portuguese.
1524* **ru:** Russian.
1525* **th:** Thai.
1526* **tr:** Turkish.
1527* **zh_CN:** Chinese.
1528
1529To submit a new translation for yargs:
1530
15311. use `./locales/en.json` as a starting point.
15322. submit a pull request with the new locale file.
1533
1534*The [Microsoft Terminology Search](http://www.microsoft.com/Language/en-US/Search.aspx) can be useful for finding the correct terminology in your locale.*
1535
1536<a name="nargs"></a>.nargs(key, count)
1537-----------
1538
1539The number of arguments that should be consumed after a key. This can be a
1540useful hint to prevent parsing ambiguity. For example:
1541
1542```js
1543var argv = require('yargs')
1544 .nargs('token', 1)
1545 .parse(['--token', '-my-token']);
1546```
1547
1548parses as:
1549
1550`{ _: [], token: '-my-token', '$0': 'node test' }`
1551
1552Optionally `.nargs()` can take an object of `key`/`narg` pairs.
1553
1554<a name="normalize"></a>.normalize(key)
1555---------------
1556
1557The key provided represents a path and should have `path.normalize()` applied.
1558
1559<a name="number"></a>.number(key)
1560------------
1561
1562Tell the parser to always interpret `key` as a number.
1563
1564If `key` is an array, all elements will be parsed as numbers.
1565
1566If the option is given on the command line without a value, `argv` will be
1567populated with `undefined`.
1568
1569If the value given on the command line cannot be parsed as a number, `argv` will
1570be populated with `NaN`.
1571
1572Note that decimals, hexadecimals, and scientific notation are all accepted.
1573
1574```js
1575var argv = require('yargs')
1576 .number('n')
1577 .number(['width', 'height'])
1578 .argv
1579```
1580
1581.option(key, [opt])
1582-----------------
1583.options(key, [opt])
1584------------------
1585
1586This method can be used to make yargs aware of options that _could_
1587exist. You can also pass an `opt` object which can hold further
1588customization, like `.alias()`, `.demandOption()` etc. for that option.
1589
1590For example:
1591
1592````javascript
1593var argv = require('yargs')
1594 .option('f', {
1595 alias: 'file',
1596 demandOption: true,
1597 default: '/etc/passwd',
1598 describe: 'x marks the spot',
1599 type: 'string'
1600 })
1601 .argv
1602;
1603````
1604
1605is the same as
1606
1607````javascript
1608var argv = require('yargs')
1609 .alias('f', 'file')
1610 .demandOption('f')
1611 .default('f', '/etc/passwd')
1612 .describe('f', 'x marks the spot')
1613 .string('f')
1614 .argv
1615;
1616````
1617
1618Optionally `.options()` can take an object that maps keys to `opt` parameters.
1619
1620````javascript
1621var argv = require('yargs')
1622 .options({
1623 'f': {
1624 alias: 'file',
1625 demandOption: true,
1626 default: '/etc/passwd',
1627 describe: 'x marks the spot',
1628 type: 'string'
1629 }
1630 })
1631 .argv
1632;
1633````
1634
1635Valid `opt` keys include:
1636
1637- `alias`: string or array of strings, alias(es) for the canonical option key, see [`alias()`](#alias)
1638- `array`: boolean, interpret option as an array, see [`array()`](#array)
1639- `boolean`: boolean, interpret option as a boolean flag, see [`boolean()`](#boolean)
1640- `choices`: value or array of values, limit valid option arguments to a predefined set, see [`choices()`](#choices)
1641- `coerce`: function, coerce or transform parsed command line values into another value, see [`coerce()`](#coerce)
1642- `config`: boolean, interpret option as a path to a JSON config file, see [`config()`](#config)
1643- `configParser`: function, provide a custom config parsing function, see [`config()`](#config)
1644- `conflicts`: string or object, require certain keys not to be set, see [`conflicts()`](#conflicts)
1645- `count`: boolean, interpret option as a count of boolean flags, see [`count()`](#count)
1646- `default`: value, set a default value for the option, see [`default()`](#default)
1647- `defaultDescription`: string, use this description for the default value in help content, see [`default()`](#default)
1648- `demandOption`: boolean or string, demand the option be given, with optional error message, see [`demandOption()`](#demandOption)
1649- `desc`/`describe`/`description`: string, the option description for help content, see [`describe()`](#describe)
1650- `global`: boolean, indicate that this key should not be [reset](#reset) when a command is invoked, see [`global()`](#global)
1651- `group`: string, when displaying usage instructions place the option under an alternative group heading, see [`group()`](#group)
1652- `implies`: string or object, require certain keys to be set, see [`implies()`](#implies)
1653- `nargs`: number, specify how many arguments should be consumed for the option, see [`nargs()`](#nargs)
1654- `normalize`: boolean, apply `path.normalize()` to the option, see [`normalize()`](#normalize)
1655- `number`: boolean, interpret option as a number, [`number()`](#number)
1656- `requiresArg`: boolean, require the option be specified with a value, see [`requiresArg()`](#requiresArg)
1657- `skipValidation`: boolean, skips validation if the option is present, see [`skipValidation()`](#skipValidation)
1658- `string`: boolean, interpret option as a string, see [`string()`](#string)
1659- `type`: one of the following strings
1660 - `'array'`: synonymous for `array: true`, see [`array()`](#array)
1661 - `'boolean'`: synonymous for `boolean: true`, see [`boolean()`](#boolean)
1662 - `'count'`: synonymous for `count: true`, see [`count()`](#count)
1663 - `'number'`: synonymous for `number: true`, see [`number()`](#number)
1664 - `'string'`: synonymous for `string: true`, see [`string()`](#string)
1665
1666.parse(args, [context], [parseCallback])
1667------------
1668
1669Parse `args` instead of `process.argv`. Returns the `argv` object.
1670`args` may either be a pre-processed argv array, or a raw argument string.
1671
1672A `context` object can optionally be given as the second argument to `parse()`, providing a
1673useful mechanism for passing state information to commands:
1674
1675```js
1676const parser = yargs
1677 .command('lunch-train <restaurant>', 'start lunch train', function () {}, function (argv) {
1678 console.log(argv.restaurant, argv.time)
1679 })
1680 .parse("lunch-train rudy's", {time: '12:15'})
1681```
1682
1683A `parseCallback` can also be provided to `.parse()`. If a callback is given, it will be invoked with three arguments:
1684
16851. `err`: populated if any validation errors raised while parsing.
16862. `argv`: the parsed argv object.
16873. `output`: any text that would have been output to the terminal, had a
1688 callback not been provided.
1689
1690```js
1691// providing the `fn` argument to `parse()` runs yargs in headless mode, this
1692// makes it easy to use yargs in contexts other than the CLI, e.g., writing
1693// a chat-bot.
1694const parser = yargs
1695 .command('lunch-train <restaurant> <time>', 'start lunch train', function () {}, function (argv) {
1696 api.scheduleLunch(argv.restaurant, moment(argv.time))
1697 })
1698 .help()
1699
1700parser.parse(bot.userText, function (err, argv, output) {
1701 if (output) bot.respond(output)
1702})
1703```
1704
1705***Note:*** Providing a callback to `parse()` disables the [`exitProcess` setting](#exitprocess) until after the callback is invoked.
1706
1707.pkgConf(key, [cwd])
1708------------
1709
1710Similar to [`config()`](#config), indicates that yargs should interpret the object from the specified key in package.json
1711as a configuration object.
1712
1713`cwd` can optionally be provided, the package.json will be read
1714from this location.
1715
1716.recommendCommands()
1717---------------------------
1718
1719Should yargs provide suggestions regarding similar commands if no matching
1720command is found?
1721
1722.require(key, [msg | boolean])
1723------------------------------
1724.required(key, [msg | boolean])
1725------------------------------
1726
1727An alias for [`demand()`](#demand). See docs there.
1728
1729<a name="requiresArg"></a>.requiresArg(key)
1730-----------------
1731
1732Specifies either a single option key (string), or an array of options that
1733must be followed by option values. If any option value is missing, show the
1734usage information and exit.
1735
1736The default behavior is to set the value of any key not followed by an
1737option value to `true`.
1738
1739<a name="reset"></a>.reset()
1740--------
1741
1742Reset the argument object built up so far. This is useful for
1743creating nested command line interfaces. Use [global](#global)
1744to specify keys that should not be reset.
1745
1746```js
1747var yargs = require('yargs')
1748 .usage('$0 command')
1749 .command('hello', 'hello command')
1750 .command('world', 'world command')
1751 .demandCommand(1, 'must provide a valid command'),
1752 argv = yargs.argv,
1753 command = argv._[0];
1754
1755if (command === 'hello') {
1756 yargs.reset()
1757 .usage('$0 hello')
1758 .help('h')
1759 .example('$0 hello', 'print the hello message!')
1760 .argv
1761
1762 console.log('hello!');
1763} else if (command === 'world'){
1764 yargs.reset()
1765 .usage('$0 world')
1766 .help('h')
1767 .example('$0 world', 'print the world message!')
1768 .argv
1769
1770 console.log('world!');
1771} else {
1772 yargs.showHelp();
1773}
1774```
1775
1776.showCompletionScript()
1777----------------------
1778
1779Generate a bash completion script. Users of your application can install this
1780script in their `.bashrc`, and yargs will provide completion shortcuts for
1781commands and options.
1782
1783.showHelp(consoleLevel='error')
1784---------------------------
1785
1786Print the usage data using the [`console`](https://nodejs.org/api/console.html) function `consoleLevel` for printing.
1787
1788Example:
1789
1790```js
1791var yargs = require("yargs")
1792 .usage("$0 -operand1 number -operand2 number -operation [add|subtract]");
1793yargs.showHelp(); //prints to stderr using console.error()
1794```
1795
1796Or, to print the usage data to `stdout` instead, you can specify the use of `console.log`:
1797
1798```js
1799yargs.showHelp("log"); //prints to stdout using console.log()
1800```
1801
1802Later on, `argv` can be retrieved with `yargs.argv`.
1803
1804.showHelpOnFail(enable, [message])
1805----------------------------------
1806
1807By default, yargs outputs a usage string if any error is detected. Use the
1808`.showHelpOnFail()` method to customize this behavior. If `enable` is `false`,
1809the usage string is not output. If the `message` parameter is present, this
1810message is output after the error message.
1811
1812line_count.js:
1813
1814````javascript
1815#!/usr/bin/env node
1816var argv = require('yargs')
1817 .usage('Count the lines in a file.\nUsage: $0 -f <file>')
1818 .demandOption('f')
1819 .alias('f', 'file')
1820 .describe('f', 'Load a file')
1821 .string('f')
1822 .showHelpOnFail(false, 'Specify --help for available options')
1823 .help('help')
1824 .argv;
1825
1826// etc.
1827````
1828
1829***
1830
1831```
1832$ node line_count.js
1833Missing argument value: f
1834
1835Specify --help for available options
1836```
1837
1838<a name="skipValidation"></a>.skipValidation(key)
1839-----------------
1840
1841Specifies either a single option key (string), or an array of options.
1842If any of the options is present, yargs validation is skipped.
1843
1844.strict([enabled=true])
1845---------
1846
1847Any command-line argument given that is not demanded, or does not have a
1848corresponding description, will be reported as an error.
1849
1850`global` indicates whether `strict()` should be enabled both
1851at the top-level and for each sub-command.
1852
1853<a name="string"></a>.string(key)
1854------------
1855
1856Tell the parser logic not to interpret `key` as a number or boolean.
1857This can be useful if you need to preserve leading zeros in an input.
1858
1859If `key` is an array, interpret all the elements as strings.
1860
1861`.string('_')` will result in non-hyphenated arguments being interpreted as strings,
1862regardless of whether they resemble numbers.
1863
1864.updateLocale(obj)
1865------------------
1866.updateStrings(obj)
1867------------------
1868
1869Override the default strings used by yargs with the key/value
1870pairs provided in `obj`:
1871
1872```js
1873var argv = require('yargs')
1874 .command('run', 'the run command')
1875 .help('help')
1876 .updateStrings({
1877 'Commands:': 'My Commands -->\n'
1878 })
1879 .wrap(null)
1880 .argv
1881```
1882
1883***
1884
1885```shell
1886My Commands -->
1887
1888 run the run command
1889
1890Options:
1891 --help Show help [boolean]
1892```
1893
1894If you explicitly specify a `locale()`, you should do so *before* calling
1895`updateStrings()`.
1896
1897.usage(message, [opts])
1898---------------------
1899
1900Set a usage message to show which commands to use. Inside `message`, the string
1901`$0` will get interpolated to the current script name or node command for the
1902present script similar to how `$0` works in bash or perl.
1903
1904`opts` is optional and acts like calling `.options(opts)`.
1905
1906<a name="version"></a>.version([option], [description], [version])
1907----------------------------------------
1908
1909Add an option (e.g. `--version`) that displays the version number (given by the
1910`version` parameter) and exits the process.
1911
1912If no arguments are passed to `version` (`.version()`), yargs will parse the `package.json`
1913of your module and use its `version` value. The default value of `option` is `--version`.
1914
1915You can provide a `function` for version, rather than a string.
1916This is useful if you want to use a version stored in a location other than package.json:
1917
1918```js
1919var argv = require('yargs')
1920 .version(function() {
1921 return require('../lib/version').version;
1922 })
1923 .argv;
1924```
1925
1926<a name="wrap"></a>.wrap(columns)
1927--------------
1928
1929Format usage output to wrap at `columns` many columns.
1930
1931By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to
1932specify no column limit (no right-align). Use `.wrap(yargs.terminalWidth())` to
1933maximize the width of yargs' usage instructions.
1934
1935parsing tricks
1936==============
1937
1938stop parsing
1939------------
1940
1941Use `--` to stop parsing flags and stuff the remainder into `argv['--']`.
1942
1943 $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4
1944 { _: [ '-c', '3', '-d', '4' ],
1945 a: 1,
1946 b: 2,
1947 '$0': 'examples/reflect.js' }
1948
1949negate fields
1950-------------
1951
1952If you want to explicitly set a field to false instead of just leaving it
1953undefined or to override a default you can do `--no-key`.
1954
1955 $ node examples/reflect.js -a --no-b
1956 { _: [], a: true, b: false, '$0': 'examples/reflect.js' }
1957
1958numbers
1959-------
1960
1961Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to
1962one. This way you can just `net.createConnection(argv.port)` and you can add
1963numbers out of `argv` with `+` without having that mean concatenation,
1964which is super frustrating.
1965
1966duplicates
1967----------
1968
1969If you specify a flag multiple times it will get turned into an array containing
1970all the values in order.
1971
1972 $ node examples/reflect.js -x 5 -x 8 -x 0
1973 { _: [], x: [ 5, 8, 0 ], '$0': 'examples/reflect.js' }
1974
1975dot notation
1976------------
1977
1978When you use dots (`.`s) in argument names, an implicit object path is assumed.
1979This lets you organize arguments into nested objects.
1980
1981 $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5
1982 { _: [],
1983 foo: { bar: { baz: 33 }, quux: 5 },
1984 '$0': 'examples/reflect.js' }
1985
1986short numbers
1987-------------
1988
1989Short numeric `-n5` style arguments work too:
1990
1991 $ node examples/reflect.js -n123 -m456
1992 { _: [], n: 123, m: 456, '$0': 'examples/reflect.js' }
1993
1994installation
1995============
1996
1997With [npm](https://github.com/npm/npm), just do:
1998
1999 npm install yargs
2000
2001or clone this project on github:
2002
2003 git clone http://github.com/yargs/yargs.git
2004
2005To run the tests with npm, just do:
2006
2007 npm test
2008
2009configuration
2010=============
2011
2012Using the `yargs` stanza in your `package.json` you can turn on and off
2013some of yargs' parsing features:
2014
2015```json
2016{
2017 "yargs": {
2018 "short-option-groups": true,
2019 "camel-case-expansion": true,
2020 "dot-notation": true,
2021 "parse-numbers": true,
2022 "boolean-negation": true
2023 }
2024}
2025```
2026
2027See the [yargs-parser](https://github.com/yargs/yargs-parser#configuration) module
2028for detailed documentation of this feature.
2029
2030inspired by
2031===========
2032
2033This module is loosely inspired by Perl's
2034[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).
2035
2036[travis-url]: https://travis-ci.org/yargs/yargs
2037[travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg
2038[coveralls-url]: https://coveralls.io/github/yargs/yargs
2039[coveralls-image]: https://img.shields.io/coveralls/yargs/yargs.svg
2040[npm-url]: https://www.npmjs.com/package/yargs
2041[npm-image]: https://img.shields.io/npm/v/yargs.svg
2042[windows-url]: https://ci.appveyor.com/project/bcoe/yargs-ljwvf
2043[windows-image]: https://img.shields.io/appveyor/ci/bcoe/yargs-ljwvf/master.svg?label=Windows%20Tests
2044[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
2045[standard-url]: http://standardjs.com/
2046[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg
2047[conventional-commits-url]: https://conventionalcommits.org/
2048[gitter-image]: https://img.shields.io/gitter/room/nwjs/nw.js.svg?maxAge=2592000
2049[gitter-url]: https://gitter.im/yargs/Lobby?utm_source=share-link&utm_medium=link&utm_campaign=share-link