UNPKG

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