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.

513 lines
10 KiB

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