e965bed943de0c9c32aab41224c2e282a6e247a052257ed8ec2f3a1ea3684f3abd164449255dd52599d239b415c7637c705bc52583217223ec4b0a86dc28a5 7.4 KB

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