You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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