3 I don't want to maintain this module anymore since I just use
4 [minimist](https://npmjs.org/package/minimist), the argument parsing engine,
5 directly instead nowadays.
7 See [yargs](https://github.com/chevex/yargs) for the modern, pirate-themed
10 [![yarrrrrrrgs!](http://i.imgur.com/4WFGVJ9.png)](https://github.com/chevex/yargs)
12 You should also consider [nomnom](https://github.com/harthur/nomnom).
17 Optimist is a node.js library for option parsing for people who hate option
18 parsing. More specifically, this module is for people who like all the --bells
19 and -whistlz of program usage but think optstrings are a waste of time.
21 With optimist, option parsing doesn't have to suck (as much).
23 [![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist)
28 With Optimist, the options are just a hash! No optstrings attached.
29 -------------------------------------------------------------------
35 var argv = require('optimist').argv;
37 if (argv.rif - 5 * argv.xup > 7.138) {
38 console.log('Buy more riffiwobbles');
41 console.log('Sell the xupptumblers');
47 $ ./xup.js --rif=55 --xup=9.52
50 $ ./xup.js --rif 12 --xup 8.1
53 ![This one's optimistic.](http://substack.net/images/optimistic.png)
55 But wait! There's more! You can do short options:
56 -------------------------------------------------
62 var argv = require('optimist').argv;
63 console.log('(%d,%d)', argv.x, argv.y);
68 $ ./short.js -x 10 -y 21
71 And booleans, both long and short (and grouped):
72 ----------------------------------
78 var util = require('util');
79 var argv = require('optimist').argv;
82 util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');
85 (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')
100 And non-hypenated options too! Just use `argv._`!
101 -------------------------------------------------
107 var argv = require('optimist').argv;
108 console.log('(%d,%d)', argv.x, argv.y);
114 $ ./nonopt.js -x 6.82 -y 3.35 moo
118 $ ./nonopt.js foo -x 0.54 bar -y 1.12 baz
120 [ 'foo', 'bar', 'baz' ]
122 Plus, Optimist comes with .usage() and .demand()!
123 -------------------------------------------------
129 var argv = require('optimist')
130 .usage('Usage: $0 -x [num] -y [num]')
134 console.log(argv.x / argv.y);
139 $ ./divide.js -x 55 -y 11
142 $ node ./divide.js -x 4.91 -z 2.51
143 Usage: node ./divide.js -x [num] -y [num]
149 Missing required arguments: y
158 var argv = require('optimist')
163 console.log(argv.x + argv.y);
168 $ ./default_singles.js -x 5
175 var argv = require('optimist')
176 .default({ x : 10, y : 10 })
179 console.log(argv.x + argv.y);
184 $ ./default_hash.js -y 7
187 And if you really want to get all descriptive about it...
188 ---------------------------------------------------------
194 var argv = require('optimist')
203 $ ./boolean_single.js -v foo bar baz
205 [ 'bar', 'baz', 'foo' ]
211 var argv = require('optimist')
212 .boolean(['x','y','z'])
215 console.dir([ argv.x, argv.y, argv.z ]);
221 $ ./boolean_double.js -x -z one two three
222 [ true, false, true ]
223 [ 'one', 'two', 'three' ]
225 Optimist is here to help...
226 ---------------------------
228 You can describe parameters for help messages and set aliases. Optimist figures
229 out how to format a handy help string automatically.
235 var argv = require('optimist')
236 .usage('Count the lines in a file.\nUsage: $0')
239 .describe('f', 'Load a file')
243 var fs = require('fs');
244 var s = fs.createReadStream(argv.file);
247 s.on('data', function (buf) {
248 lines += buf.toString().match(/\n/g).length;
251 s.on('end', function () {
259 Count the lines in a file.
260 Usage: node ./line_count.js
263 -f, --file Load a file [required]
265 Missing required arguments: f
267 $ node line_count.js --file line_count.js
270 $ node line_count.js -f line_count.js
279 require('optimist').argv
282 will use `process.argv` array to construct the `argv` object.
284 You can pass in the `process.argv` yourself:
287 require('optimist')([ '-x', '1', '-y', '2' ]).argv
290 or use .parse() to do the same thing:
293 require('optimist').parse([ '-x', '1', '-y', '2' ])
296 The rest of these methods below come in just before the terminating `.argv`.
301 Set key names as equivalent such that updates to a key will propagate to aliases
304 Optionally `.alias()` can take an object that maps keys to aliases.
309 Set `argv[key]` to `value` if no option was specified on `process.argv`.
311 Optionally `.default()` can take an object that maps keys to default values.
316 If `key` is a string, show the usage information and exit if `key` wasn't
317 specified in `process.argv`.
319 If `key` is a number, demand at least as many non-option arguments, which show
322 If `key` is an Array, demand each element.
327 Describe a `key` for the generated usage information.
329 Optionally `.describe()` can take an object that maps keys to descriptions.
334 Instead of chaining together `.alias().demand().default()`, you can specify
335 keys in `opt` for each of the chainable methods.
340 var argv = require('optimist')
343 default : '/etc/passwd',
352 var argv = require('optimist')
354 .default('f', '/etc/passwd')
359 Optionally `.options()` can take an object that maps keys to `opt` parameters.
364 Set a usage message to show which commands to use. Inside `message`, the string
365 `$0` will get interpolated to the current script name or node command for the
366 present script similar to how `$0` works in bash or perl.
371 Check that certain conditions are met in the provided arguments.
373 If `fn` throws or returns `false`, show the thrown error, usage information, and
379 Interpret `key` as a boolean. If a non-flag option follows `key` in
380 `process.argv`, that string won't get set as the value of `key`.
382 If `key` never shows up as a flag in `process.arguments`, `argv[key]` will be
385 If `key` is an Array, interpret all the elements as booleans.
390 Tell the parser logic not to interpret `key` as a number or boolean.
391 This can be useful if you need to preserve leading zeros in an input.
393 If `key` is an Array, interpret all the elements as strings.
398 Format usage output to wrap at `columns` many columns.
403 Return the generated usage string.
405 .showHelp(fn=console.error)
406 ---------------------------
408 Print the usage data using `fn` for printing.
413 Parse `args` instead of `process.argv`. Returns the `argv` object.
418 Get the arguments as a plain old object.
420 Arguments without a corresponding flag show up in the `argv._` array.
422 The script name or node command is available at `argv.$0` similarly to how `$0`
423 works in bash or perl.
431 Use `--` to stop parsing flags and stuff the remainder into `argv._`.
433 $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4
434 { _: [ '-c', '3', '-d', '4' ],
435 '$0': 'node ./examples/reflect.js',
442 If you want to explicity set a field to false instead of just leaving it
443 undefined or to override a default you can do `--no-key`.
445 $ node examples/reflect.js -a --no-b
447 '$0': 'node ./examples/reflect.js',
454 Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to
455 one. This way you can just `net.createConnection(argv.port)` and you can add
456 numbers out of `argv` with `+` without having that mean concatenation,
457 which is super frustrating.
462 If you specify a flag multiple times it will get turned into an array containing
463 all the values in order.
465 $ node examples/reflect.js -x 5 -x 8 -x 0
467 '$0': 'node ./examples/reflect.js',
473 When you use dots (`.`s) in argument names, an implicit object path is assumed.
474 This lets you organize arguments into nested objects.
476 $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5
478 '$0': 'node ./examples/reflect.js',
479 foo: { bar: { baz: 33 }, quux: 5 } }
484 Short numeric `head -n5` style argument work too:
486 $ node reflect.js -n123 -m456
490 '$0': 'node ./reflect.js',
497 With [npm](http://github.com/isaacs/npm), just do:
500 or clone this project on github:
502 git clone http://github.com/substack/node-optimist.git
504 To run the tests with [expresso](http://github.com/visionmedia/expresso),
512 This module is loosely inspired by Perl's
513 [Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).