UNPKG

10.7 kBMarkdownView Raw
1# DEPRECATION NOTICE
2
3I don't want to maintain this module anymore since I just use
4[minimist](https://npmjs.org/package/minimist), the argument parsing engine,
5directly instead nowadays.
6
7See [yargs](https://github.com/chevex/yargs) for the modern, pirate-themed
8successor to optimist.
9
10[![yarrrrrrrgs!](http://i.imgur.com/4WFGVJ9.png)](https://github.com/chevex/yargs)
11
12You should also consider [nomnom](https://github.com/harthur/nomnom).
13
14optimist
15========
16
17Optimist is a node.js library for option parsing for people who hate option
18parsing. More specifically, this module is for people who like all the --bells
19and -whistlz of program usage but think optstrings are a waste of time.
20
21With optimist, option parsing doesn't have to suck (as much).
22
23[![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist)
24
25examples
26========
27
28With Optimist, the options are just a hash! No optstrings attached.
29-------------------------------------------------------------------
30
31xup.js:
32
33````javascript
34#!/usr/bin/env node
35var argv = require('optimist').argv;
36
37if (argv.rif - 5 * argv.xup > 7.138) {
38 console.log('Buy more riffiwobbles');
39}
40else {
41 console.log('Sell the xupptumblers');
42}
43````
44
45***
46
47 $ ./xup.js --rif=55 --xup=9.52
48 Buy more riffiwobbles
49
50 $ ./xup.js --rif 12 --xup 8.1
51 Sell the xupptumblers
52
53![This one's optimistic.](http://substack.net/images/optimistic.png)
54
55But wait! There's more! You can do short options:
56-------------------------------------------------
57
58short.js:
59
60````javascript
61#!/usr/bin/env node
62var argv = require('optimist').argv;
63console.log('(%d,%d)', argv.x, argv.y);
64````
65
66***
67
68 $ ./short.js -x 10 -y 21
69 (10,21)
70
71And booleans, both long and short (and grouped):
72----------------------------------
73
74bool.js:
75
76````javascript
77#!/usr/bin/env node
78var util = require('util');
79var argv = require('optimist').argv;
80
81if (argv.s) {
82 util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');
83}
84console.log(
85 (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')
86);
87````
88
89***
90
91 $ ./bool.js -s
92 The cat says: meow
93
94 $ ./bool.js -sp
95 The cat says: meow.
96
97 $ ./bool.js -sp --fr
98 Le chat dit: miaou.
99
100And non-hypenated options too! Just use `argv._`!
101-------------------------------------------------
102
103nonopt.js:
104
105````javascript
106#!/usr/bin/env node
107var argv = require('optimist').argv;
108console.log('(%d,%d)', argv.x, argv.y);
109console.log(argv._);
110````
111
112***
113
114 $ ./nonopt.js -x 6.82 -y 3.35 moo
115 (6.82,3.35)
116 [ 'moo' ]
117
118 $ ./nonopt.js foo -x 0.54 bar -y 1.12 baz
119 (0.54,1.12)
120 [ 'foo', 'bar', 'baz' ]
121
122Plus, Optimist comes with .usage() and .demand()!
123-------------------------------------------------
124
125divide.js:
126
127````javascript
128#!/usr/bin/env node
129var argv = require('optimist')
130 .usage('Usage: $0 -x [num] -y [num]')
131 .demand(['x','y'])
132 .argv;
133
134console.log(argv.x / argv.y);
135````
136
137***
138
139 $ ./divide.js -x 55 -y 11
140 5
141
142 $ node ./divide.js -x 4.91 -z 2.51
143 Usage: node ./divide.js -x [num] -y [num]
144
145 Options:
146 -x [required]
147 -y [required]
148
149 Missing required arguments: y
150
151EVEN MORE HOLY COW
152------------------
153
154default_singles.js:
155
156````javascript
157#!/usr/bin/env node
158var argv = require('optimist')
159 .default('x', 10)
160 .default('y', 10)
161 .argv
162;
163console.log(argv.x + argv.y);
164````
165
166***
167
168 $ ./default_singles.js -x 5
169 15
170
171default_hash.js:
172
173````javascript
174#!/usr/bin/env node
175var argv = require('optimist')
176 .default({ x : 10, y : 10 })
177 .argv
178;
179console.log(argv.x + argv.y);
180````
181
182***
183
184 $ ./default_hash.js -y 7
185 17
186
187And if you really want to get all descriptive about it...
188---------------------------------------------------------
189
190boolean_single.js
191
192````javascript
193#!/usr/bin/env node
194var argv = require('optimist')
195 .boolean('v')
196 .argv
197;
198console.dir(argv);
199````
200
201***
202
203 $ ./boolean_single.js -v foo bar baz
204 true
205 [ 'bar', 'baz', 'foo' ]
206
207boolean_double.js
208
209````javascript
210#!/usr/bin/env node
211var argv = require('optimist')
212 .boolean(['x','y','z'])
213 .argv
214;
215console.dir([ argv.x, argv.y, argv.z ]);
216console.dir(argv._);
217````
218
219***
220
221 $ ./boolean_double.js -x -z one two three
222 [ true, false, true ]
223 [ 'one', 'two', 'three' ]
224
225Optimist is here to help...
226---------------------------
227
228You can describe parameters for help messages and set aliases. Optimist figures
229out how to format a handy help string automatically.
230
231line_count.js
232
233````javascript
234#!/usr/bin/env node
235var argv = require('optimist')
236 .usage('Count the lines in a file.\nUsage: $0')
237 .demand('f')
238 .alias('f', 'file')
239 .describe('f', 'Load a file')
240 .argv
241;
242
243var fs = require('fs');
244var s = fs.createReadStream(argv.file);
245
246var lines = 0;
247s.on('data', function (buf) {
248 lines += buf.toString().match(/\n/g).length;
249});
250
251s.on('end', function () {
252 console.log(lines);
253});
254````
255
256***
257
258 $ node line_count.js
259 Count the lines in a file.
260 Usage: node ./line_count.js
261
262 Options:
263 -f, --file Load a file [required]
264
265 Missing required arguments: f
266
267 $ node line_count.js --file line_count.js
268 20
269
270 $ node line_count.js -f line_count.js
271 20
272
273methods
274=======
275
276By itself,
277
278````javascript
279require('optimist').argv
280`````
281
282will use `process.argv` array to construct the `argv` object.
283
284You can pass in the `process.argv` yourself:
285
286````javascript
287require('optimist')([ '-x', '1', '-y', '2' ]).argv
288````
289
290or use .parse() to do the same thing:
291
292````javascript
293require('optimist').parse([ '-x', '1', '-y', '2' ])
294````
295
296The rest of these methods below come in just before the terminating `.argv`.
297
298.alias(key, alias)
299------------------
300
301Set key names as equivalent such that updates to a key will propagate to aliases
302and vice-versa.
303
304Optionally `.alias()` can take an object that maps keys to aliases.
305
306.default(key, value)
307--------------------
308
309Set `argv[key]` to `value` if no option was specified on `process.argv`.
310
311Optionally `.default()` can take an object that maps keys to default values.
312
313.demand(key)
314------------
315
316If `key` is a string, show the usage information and exit if `key` wasn't
317specified in `process.argv`.
318
319If `key` is a number, demand at least as many non-option arguments, which show
320up in `argv._`.
321
322If `key` is an Array, demand each element.
323
324.describe(key, desc)
325--------------------
326
327Describe a `key` for the generated usage information.
328
329Optionally `.describe()` can take an object that maps keys to descriptions.
330
331.options(key, opt)
332------------------
333
334Instead of chaining together `.alias().demand().default()`, you can specify
335keys in `opt` for each of the chainable methods.
336
337For example:
338
339````javascript
340var argv = require('optimist')
341 .options('f', {
342 alias : 'file',
343 default : '/etc/passwd',
344 })
345 .argv
346;
347````
348
349is the same as
350
351````javascript
352var argv = require('optimist')
353 .alias('f', 'file')
354 .default('f', '/etc/passwd')
355 .argv
356;
357````
358
359Optionally `.options()` can take an object that maps keys to `opt` parameters.
360
361.usage(message)
362---------------
363
364Set 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
366present script similar to how `$0` works in bash or perl.
367
368.check(fn)
369----------
370
371Check that certain conditions are met in the provided arguments.
372
373If `fn` throws or returns `false`, show the thrown error, usage information, and
374exit.
375
376.boolean(key)
377-------------
378
379Interpret `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`.
381
382If `key` never shows up as a flag in `process.arguments`, `argv[key]` will be
383`false`.
384
385If `key` is an Array, interpret all the elements as booleans.
386
387.string(key)
388------------
389
390Tell the parser logic not to interpret `key` as a number or boolean.
391This can be useful if you need to preserve leading zeros in an input.
392
393If `key` is an Array, interpret all the elements as strings.
394
395.wrap(columns)
396--------------
397
398Format usage output to wrap at `columns` many columns.
399
400.help()
401-------
402
403Return the generated usage string.
404
405.showHelp(fn=console.error)
406---------------------------
407
408Print the usage data using `fn` for printing.
409
410.parse(args)
411------------
412
413Parse `args` instead of `process.argv`. Returns the `argv` object.
414
415.argv
416-----
417
418Get the arguments as a plain old object.
419
420Arguments without a corresponding flag show up in the `argv._` array.
421
422The script name or node command is available at `argv.$0` similarly to how `$0`
423works in bash or perl.
424
425parsing tricks
426==============
427
428stop parsing
429------------
430
431Use `--` to stop parsing flags and stuff the remainder into `argv._`.
432
433 $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4
434 { _: [ '-c', '3', '-d', '4' ],
435 '$0': 'node ./examples/reflect.js',
436 a: 1,
437 b: 2 }
438
439negate fields
440-------------
441
442If you want to explicity set a field to false instead of just leaving it
443undefined or to override a default you can do `--no-key`.
444
445 $ node examples/reflect.js -a --no-b
446 { _: [],
447 '$0': 'node ./examples/reflect.js',
448 a: true,
449 b: false }
450
451numbers
452-------
453
454Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to
455one. This way you can just `net.createConnection(argv.port)` and you can add
456numbers out of `argv` with `+` without having that mean concatenation,
457which is super frustrating.
458
459duplicates
460----------
461
462If you specify a flag multiple times it will get turned into an array containing
463all the values in order.
464
465 $ node examples/reflect.js -x 5 -x 8 -x 0
466 { _: [],
467 '$0': 'node ./examples/reflect.js',
468 x: [ 5, 8, 0 ] }
469
470dot notation
471------------
472
473When you use dots (`.`s) in argument names, an implicit object path is assumed.
474This lets you organize arguments into nested objects.
475
476 $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5
477 { _: [],
478 '$0': 'node ./examples/reflect.js',
479 foo: { bar: { baz: 33 }, quux: 5 } }
480
481short numbers
482-------------
483
484Short numeric `head -n5` style argument work too:
485
486 $ node reflect.js -n123 -m456
487 { '3': true,
488 '6': true,
489 _: [],
490 '$0': 'node ./reflect.js',
491 n: 123,
492 m: 456 }
493
494installation
495============
496
497With [npm](http://github.com/isaacs/npm), just do:
498 npm install optimist
499
500or clone this project on github:
501
502 git clone http://github.com/substack/node-optimist.git
503
504To run the tests with [expresso](http://github.com/visionmedia/expresso),
505just do:
506
507 expresso
508
509inspired By
510===========
511
512This module is loosely inspired by Perl's
513[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).
514
\No newline at end of file