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.
4 The Wrong Way is to sit down and write an option parser. We've all done
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.
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
22 var nopt = require("nopt")
23 , Stream = require("stream").Stream
24 , path = require("path")
25 , knownOpts = { "foo" : [String, null]
26 , "bar" : [Stream, Number]
28 , "bloo" : [ "big", "medium", "small" ]
31 , "many" : [String, Array]
33 , shortHands = { "foofoo" : ["--foo", "Mr. Foo"]
34 , "b7" : ["--bar", "7"]
35 , "m" : ["--bloo", "medium"]
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)
46 This would give you support for any of the following:
49 $ node my-program.js --foo "blerp" --no-flag
50 { "foo" : "blerp", "flag" : false }
52 $ node my-program.js ---bar 7 --foo "Mr. Hand" --flag
53 { bar: 7, foo: "Mr. Hand", flag: true }
55 $ node my-program.js --foo "blerp" -f -----p
56 { foo: "blerp", flag: true, pick: true }
58 $ node my-program.js -fp --foofoo
59 { foo: "Mr. Foo", flag: true, pick: true }
61 $ node my-program.js --foofoo -- -fp # -- stops the flag parsing.
62 { foo: "Mr. Foo", argv: { remain: ["-fp"] } }
64 $ node my-program.js --blatzk 1000 -fp # unknown opts are ok.
65 { blatzk: 1000, flag: true, pick: true }
67 $ node my-program.js --blatzk true -fp # but they need a value
68 { blatzk: true, flag: true, pick: true }
70 $ node my-program.js --no-blatzk -fp # unless they start with "no-"
71 { blatzk: false, flag: true, pick: true }
73 $ node my-program.js --baz b/a/z # known paths are resolved.
74 { baz: "/Users/isaacs/b/a/z" }
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.
80 $ node my-program.js --many 1 --many null --many foo
81 { many: ["1", "null", "foo"] }
83 $ node my-program.js --many foo
87 Read the tests at the bottom of `lib/nopt.js` for more examples of
88 what this puppy can do.
92 The following types are supported, and defined on `nopt.typeDefs`
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.
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.
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
104 * NaN: Means that the option is strictly not allowed. Any value will
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.)
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.
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.
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.
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
124 either a Number or null.
126 To define a new type, add it to `nopt.typeDefs`. Each item in that
127 hash is an object with a `type` member and a `validate` method. The
128 `type` member is an object that matches what goes in the type list. The
129 `validate` method is a function that gets called with `validate(data,
130 key, val)`. Validate methods should assign `data[key]` to the valid
131 value of `val` if it can be handled properly, or return boolean
132 `false` if it cannot.
134 You can also call `nopt.clean(data, types, typeDefs)` to clean up a
135 config object and remove its invalid properties.
139 By default, nopt outputs a warning to standard error when invalid
140 options are found. You can change this behavior by assigning a method
141 to `nopt.invalidHandler`. This method will be called with
142 the offending `nopt.invalidHandler(key, val, types)`.
144 If no `nopt.invalidHandler` is assigned, then it will console.error
145 its whining. If it is assigned to boolean `false` then the warning is
150 Yes, they are supported. If you define options like this:
153 { "foolhardyelephants" : Boolean
154 , "pileofmonkeys" : Boolean }
160 node program.js --foolhar --pil
161 node program.js --no-f --pileofmon
167 Shorthands are a hash of shorter option names to a snippet of args that
170 If multiple one-character shorthands are all combined, and the
171 combination does not unambiguously match any other option or shorthand,
172 then they will be broken up into their constituent parts. For example:
175 { "s" : ["--loglevel", "silent"]
178 , "p" : "--parseable"
185 # just like doing this:
186 npm ls --loglevel silent --global --force --long --parseable
189 ## The Rest of the args
191 The config object returned by nopt is given a special member called
192 `argv`, which is an object with the following fields:
194 * `remain`: The remaining args after all the parsing has occurred.
195 * `original`: The args as they originally appeared.
196 * `cooked`: The args after flags and shorthands are expanded.
200 Node programs are called with more or less the exact argv as it appears
201 in C land, after the v8 and node-specific options have been plucked off.
202 As such, `argv[0]` is always `node` and `argv[1]` is always the
203 JavaScript program being run.
205 That's usually not very useful to you. So they're sliced off by
206 default. If you want them, then you can pass in `0` as the last
207 argument, or any other number that you'd like to slice off the start of