You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 54KB

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