Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 211 lines (164 sloc) 7.61 kb
1b1237c @isaacs first!
isaacs authored
1 If you want to write an option parser, and have it be good, there are
2 two ways to do it. The Right Way, and the Wrong Way.
3
4 The Wrong Way is to sit down and write an option parser. We've all done
5 that.
6
7 The Right Way is to write some complex configurable program with so many
8 options that you go half-insane just trying to manage them all, and put
9 it off with duct-tape solutions until you see exactly to the core of the
10 problem, and finally snap and write an awesome option parser.
11
12 If you want to write an option parser, don't write an option parser.
13 Write a package manager, or a source control system, or a service
14 restarter, or an operating system. You probably won't end up with a
15 good one of those, but if you don't give up, and you are relentless and
16 diligent enough in your procrastination, you may just end up with a very
17 nice option parser.
18
19 ## USAGE
20
ec08a41 @isaacs Closes GH-1 Collisions between shorthands and abbrevs could cause failur...
isaacs authored
21 // my-program.js
1b1237c @isaacs first!
isaacs authored
22 var nopt = require("nopt")
23 , Stream = require("stream").Stream
24 , path = require("path")
25 , knownOpts = { "foo" : [String, null]
26 , "bar" : [Stream, Number]
27 , "baz" : path
28 , "bloo" : [ "big", "medium", "small" ]
29 , "flag" : Boolean
30 , "pick" : Boolean
b07889d @isaacs Update readme
isaacs authored
31 , "many" : [String, Array]
1b1237c @isaacs first!
isaacs authored
32 }
33 , shortHands = { "foofoo" : ["--foo", "Mr. Foo"]
34 , "b7" : ["--bar", "7"]
35 , "m" : ["--bloo", "medium"]
36 , "p" : ["--pick"]
37 , "f" : ["--flag"]
38 }
39 // everything is optional.
40 // knownOpts and shorthands default to {}
41 // arg list defaults to process.argv
42 // slice defaults to 2
43 , parsed = nopt(knownOpts, shortHands, process.argv, 2)
ec08a41 @isaacs Closes GH-1 Collisions between shorthands and abbrevs could cause failur...
isaacs authored
44 console.log(parsed)
1b1237c @isaacs first!
isaacs authored
45
46 This would give you support for any of the following:
47
b07889d @isaacs Update readme
isaacs authored
48 ```bash
49 $ node my-program.js --foo "blerp" --no-flag
50 { "foo" : "blerp", "flag" : false }
1b1237c @isaacs first!
isaacs authored
51
b07889d @isaacs Update readme
isaacs authored
52 $ node my-program.js ---bar 7 --foo "Mr. Hand" --flag
53 { bar: 7, foo: "Mr. Hand", flag: true }
1b1237c @isaacs first!
isaacs authored
54
b07889d @isaacs Update readme
isaacs authored
55 $ node my-program.js --foo "blerp" -f -----p
56 { foo: "blerp", flag: true, pick: true }
1b1237c @isaacs first!
isaacs authored
57
b07889d @isaacs Update readme
isaacs authored
58 $ node my-program.js -fp --foofoo
59 { foo: "Mr. Foo", flag: true, pick: true }
1b1237c @isaacs first!
isaacs authored
60
b07889d @isaacs Update readme
isaacs authored
61 $ node my-program.js --foofoo -- -fp # -- stops the flag parsing.
62 { foo: "Mr. Foo", argv: { remain: ["-fp"] } }
1b1237c @isaacs first!
isaacs authored
63
b07889d @isaacs Update readme
isaacs authored
64 $ node my-program.js --blatzk 1000 -fp # unknown opts are ok.
65 { blatzk: 1000, flag: true, pick: true }
1b1237c @isaacs first!
isaacs authored
66
b07889d @isaacs Update readme
isaacs authored
67 $ node my-program.js --blatzk true -fp # but they need a value
68 { blatzk: true, flag: true, pick: true }
1b1237c @isaacs first!
isaacs authored
69
b07889d @isaacs Update readme
isaacs authored
70 $ node my-program.js --no-blatzk -fp # unless they start with "no-"
71 { blatzk: false, flag: true, pick: true }
1b1237c @isaacs first!
isaacs authored
72
b07889d @isaacs Update readme
isaacs authored
73 $ node my-program.js --baz b/a/z # known paths are resolved.
74 { baz: "/Users/isaacs/b/a/z" }
75
76 # if Array is one of the types, then it can take many
77 # values, and will always be an array. The other types provided
78 # specify what types are allowed in the list.
79
80 $ node my-program.js --many 1 --many null --many foo
81 { many: ["1", "null", "foo"] }
82
83 $ node my-program.js --many foo
84 { many: ["foo"] }
85 ```
1b1237c @isaacs first!
isaacs authored
86
87 Read the tests at the bottom of `lib/nopt.js` for more examples of
88 what this puppy can do.
89
90 ## Types
91
92 The following types are supported, and defined on `nopt.typeDefs`
93
94 * String: A normal string. No parsing is done.
95 * path: A file system path. Gets resolved against cwd if not absolute.
96 * url: A url. If it doesn't parse, it isn't accepted.
35a874b @isaacs Add date awareness to nopt
isaacs authored
97 * Number: Must be numeric.
98 * Date: Must parse as a date. If it does, and `Date` is one of the options,
99 then it will return a Date object, not a string.
1b1237c @isaacs first!
isaacs authored
100 * Boolean: Must be either `true` or `false`. If an option is a boolean,
101 then it does not need a value, and its presence will imply `true` as
102 the value. To negate boolean flags, do `--no-whatever` or `--whatever
103 false`
104 * NaN: Means that the option is strictly not allowed. Any value will
105 fail.
106 * Stream: An object matching the "Stream" class in node. Valuable
107 for use when validating programmatically. (npm uses this to let you
108 supply any WriteStream on the `outfd` and `logfd` config options.)
b07889d @isaacs Update readme
isaacs authored
109 * Array: If `Array` is specified as one of the types, then the value
110 will be parsed as a list of options. This means that multiple values
111 can be specified, and that the value will always be an array.
1b1237c @isaacs first!
isaacs authored
112
113 If a type is an array of values not on this list, then those are
114 considered valid values. For instance, in the example above, the
115 `--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`,
116 and any other value will be rejected.
117
118 When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be
119 interpreted as their JavaScript equivalents, and numeric values will be
120 interpreted as a number.
121
122 You can also mix types and values, or multiple types, in a list. For
123 instance `{ blah: [Number, null] }` would allow a value to be set to
6edc048 @isaacs Explain ordering of types
isaacs authored
124 either a Number or null. When types are ordered, this implies a
125 preference, and the first type that can be used to properly interpret
126 the value will be used.
1b1237c @isaacs first!
isaacs authored
127
128 To define a new type, add it to `nopt.typeDefs`. Each item in that
129 hash is an object with a `type` member and a `validate` method. The
130 `type` member is an object that matches what goes in the type list. The
131 `validate` method is a function that gets called with `validate(data,
132 key, val)`. Validate methods should assign `data[key]` to the valid
133 value of `val` if it can be handled properly, or return boolean
134 `false` if it cannot.
135
136 You can also call `nopt.clean(data, types, typeDefs)` to clean up a
137 config object and remove its invalid properties.
138
139 ## Error Handling
140
141 By default, nopt outputs a warning to standard error when invalid
142 options are found. You can change this behavior by assigning a method
143 to `nopt.invalidHandler`. This method will be called with
144 the offending `nopt.invalidHandler(key, val, types)`.
145
146 If no `nopt.invalidHandler` is assigned, then it will console.error
147 its whining. If it is assigned to boolean `false` then the warning is
148 suppressed.
149
150 ## Abbreviations
151
152 Yes, they are supported. If you define options like this:
153
b07889d @isaacs Update readme
isaacs authored
154 ```javascript
155 { "foolhardyelephants" : Boolean
156 , "pileofmonkeys" : Boolean }
157 ```
1b1237c @isaacs first!
isaacs authored
158
159 Then this will work:
160
b07889d @isaacs Update readme
isaacs authored
161 ```bash
162 node program.js --foolhar --pil
163 node program.js --no-f --pileofmon
164 # etc.
165 ```
1b1237c @isaacs first!
isaacs authored
166
167 ## Shorthands
168
169 Shorthands are a hash of shorter option names to a snippet of args that
170 they expand to.
171
172 If multiple one-character shorthands are all combined, and the
173 combination does not unambiguously match any other option or shorthand,
174 then they will be broken up into their constituent parts. For example:
175
b07889d @isaacs Update readme
isaacs authored
176 ```json
177 { "s" : ["--loglevel", "silent"]
178 , "g" : "--global"
179 , "f" : "--force"
180 , "p" : "--parseable"
181 , "l" : "--long"
182 }
183 ```
184
185 ```bash
186 npm ls -sgflp
187 # just like doing this:
188 npm ls --loglevel silent --global --force --long --parseable
189 ```
1b1237c @isaacs first!
isaacs authored
190
191 ## The Rest of the args
192
193 The config object returned by nopt is given a special member called
194 `argv`, which is an object with the following fields:
195
196 * `remain`: The remaining args after all the parsing has occurred.
197 * `original`: The args as they originally appeared.
198 * `cooked`: The args after flags and shorthands are expanded.
199
200 ## Slicing
201
202 Node programs are called with more or less the exact argv as it appears
203 in C land, after the v8 and node-specific options have been plucked off.
204 As such, `argv[0]` is always `node` and `argv[1]` is always the
205 JavaScript program being run.
206
207 That's usually not very useful to you. So they're sliced off by
208 default. If you want them, then you can pass in `0` as the last
209 argument, or any other number that you'd like to slice off the start of
210 the list.
Something went wrong with that request. Please try again.