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.

317 lines
6.5 KiB

2 years ago
  1. # Arg
  2. `arg` is an unopinionated, no-frills CLI argument parser.
  3. ## Installation
  4. ```bash
  5. npm install arg
  6. ```
  7. ## Usage
  8. `arg()` takes either 1 or 2 arguments:
  9. 1. Command line specification object (see below)
  10. 2. Parse options (_Optional_, defaults to `{permissive: false, argv: process.argv.slice(2), stopAtPositional: false}`)
  11. It returns an object with any values present on the command-line (missing options are thus
  12. missing from the resulting object). Arg performs no validation/requirement checking - we
  13. leave that up to the application.
  14. All parameters that aren't consumed by options (commonly referred to as "extra" parameters)
  15. are added to `result._`, which is _always_ an array (even if no extra parameters are passed,
  16. in which case an empty array is returned).
  17. ```javascript
  18. const arg = require('arg');
  19. // `options` is an optional parameter
  20. const args = arg(
  21. spec,
  22. (options = { permissive: false, argv: process.argv.slice(2) })
  23. );
  24. ```
  25. For example:
  26. ```console
  27. $ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar
  28. ```
  29. ```javascript
  30. // hello.js
  31. const arg = require('arg');
  32. const args = arg({
  33. // Types
  34. '--help': Boolean,
  35. '--version': Boolean,
  36. '--verbose': arg.COUNT, // Counts the number of times --verbose is passed
  37. '--port': Number, // --port <number> or --port=<number>
  38. '--name': String, // --name <string> or --name=<string>
  39. '--tag': [String], // --tag <string> or --tag=<string>
  40. // Aliases
  41. '-v': '--verbose',
  42. '-n': '--name', // -n <string>; result is stored in --name
  43. '--label': '--name' // --label <string> or --label=<string>;
  44. // result is stored in --name
  45. });
  46. console.log(args);
  47. /*
  48. {
  49. _: ["foo", "bar", "--foobar"],
  50. '--port': 1234,
  51. '--verbose': 4,
  52. '--name': "My name",
  53. '--tag': ["qux", "qix"]
  54. }
  55. */
  56. ```
  57. The values for each key=&gt;value pair is either a type (function or [function]) or a string (indicating an alias).
  58. - In the case of a function, the string value of the argument's value is passed to it,
  59. and the return value is used as the ultimate value.
  60. - In the case of an array, the only element _must_ be a type function. Array types indicate
  61. that the argument may be passed multiple times, and as such the resulting value in the returned
  62. object is an array with all of the values that were passed using the specified flag.
  63. - In the case of a string, an alias is established. If a flag is passed that matches the _key_,
  64. then the _value_ is substituted in its place.
  65. Type functions are passed three arguments:
  66. 1. The parameter value (always a string)
  67. 2. The parameter name (e.g. `--label`)
  68. 3. The previous value for the destination (useful for reduce-like operations or for supporting `-v` multiple times, etc.)
  69. This means the built-in `String`, `Number`, and `Boolean` type constructors "just work" as type functions.
  70. Note that `Boolean` and `[Boolean]` have special treatment - an option argument is _not_ consumed or passed, but instead `true` is
  71. returned. These options are called "flags".
  72. For custom handlers that wish to behave as flags, you may pass the function through `arg.flag()`:
  73. ```javascript
  74. const arg = require('arg');
  75. const argv = [
  76. '--foo',
  77. 'bar',
  78. '-ff',
  79. 'baz',
  80. '--foo',
  81. '--foo',
  82. 'qux',
  83. '-fff',
  84. 'qix'
  85. ];
  86. function myHandler(value, argName, previousValue) {
  87. /* `value` is always `true` */
  88. return 'na ' + (previousValue || 'batman!');
  89. }
  90. const args = arg(
  91. {
  92. '--foo': arg.flag(myHandler),
  93. '-f': '--foo'
  94. },
  95. {
  96. argv
  97. }
  98. );
  99. console.log(args);
  100. /*
  101. {
  102. _: ['bar', 'baz', 'qux', 'qix'],
  103. '--foo': 'na na na na na na na na batman!'
  104. }
  105. */
  106. ```
  107. As well, `arg` supplies a helper argument handler called `arg.COUNT`, which equivalent to a `[Boolean]` argument's `.length`
  108. property - effectively counting the number of times the boolean flag, denoted by the key, is passed on the command line..
  109. For example, this is how you could implement `ssh`'s multiple levels of verbosity (`-vvvv` being the most verbose).
  110. ```javascript
  111. const arg = require('arg');
  112. const argv = ['-AAAA', '-BBBB'];
  113. const args = arg(
  114. {
  115. '-A': arg.COUNT,
  116. '-B': [Boolean]
  117. },
  118. {
  119. argv
  120. }
  121. );
  122. console.log(args);
  123. /*
  124. {
  125. _: [],
  126. '-A': 4,
  127. '-B': [true, true, true, true]
  128. }
  129. */
  130. ```
  131. ### Options
  132. If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of `arg()`.
  133. #### `argv`
  134. If you have already sliced or generated a number of raw arguments to be parsed (as opposed to letting `arg`
  135. slice them from `process.argv`) you may specify them in the `argv` option.
  136. For example:
  137. ```javascript
  138. const args = arg(
  139. {
  140. '--foo': String
  141. },
  142. {
  143. argv: ['hello', '--foo', 'world']
  144. }
  145. );
  146. ```
  147. results in:
  148. ```javascript
  149. const args = {
  150. _: ['hello'],
  151. '--foo': 'world'
  152. };
  153. ```
  154. #### `permissive`
  155. When `permissive` set to `true`, `arg` will push any unknown arguments
  156. onto the "extra" argument array (`result._`) instead of throwing an error about
  157. an unknown flag.
  158. For example:
  159. ```javascript
  160. const arg = require('arg');
  161. const argv = [
  162. '--foo',
  163. 'hello',
  164. '--qux',
  165. 'qix',
  166. '--bar',
  167. '12345',
  168. 'hello again'
  169. ];
  170. const args = arg(
  171. {
  172. '--foo': String,
  173. '--bar': Number
  174. },
  175. {
  176. argv,
  177. permissive: true
  178. }
  179. );
  180. ```
  181. results in:
  182. ```javascript
  183. const args = {
  184. _: ['--qux', 'qix', 'hello again'],
  185. '--foo': 'hello',
  186. '--bar': 12345
  187. };
  188. ```
  189. #### `stopAtPositional`
  190. When `stopAtPositional` is set to `true`, `arg` will halt parsing at the first
  191. positional argument.
  192. For example:
  193. ```javascript
  194. const arg = require('arg');
  195. const argv = ['--foo', 'hello', '--bar'];
  196. const args = arg(
  197. {
  198. '--foo': Boolean,
  199. '--bar': Boolean
  200. },
  201. {
  202. argv,
  203. stopAtPositional: true
  204. }
  205. );
  206. ```
  207. results in:
  208. ```javascript
  209. const args = {
  210. _: ['hello', '--bar'],
  211. '--foo': true
  212. };
  213. ```
  214. ### Errors
  215. Some errors that `arg` throws provide a `.code` property in order to aid in recovering from user error, or to
  216. differentiate between user error and developer error (bug).
  217. ##### ARG_UNKNOWN_OPTION
  218. If an unknown option (not defined in the spec object) is passed, an error with code `ARG_UNKNOWN_OPTION` will be thrown:
  219. ```js
  220. // cli.js
  221. try {
  222. require('arg')({ '--hi': String });
  223. } catch (err) {
  224. if (err.code === 'ARG_UNKNOWN_OPTION') {
  225. console.log(err.message);
  226. } else {
  227. throw err;
  228. }
  229. }
  230. ```
  231. ```shell
  232. node cli.js --extraneous true
  233. Unknown or unexpected option: --extraneous
  234. ```
  235. # FAQ
  236. A few questions and answers that have been asked before:
  237. ### How do I require an argument with `arg`?
  238. Do the assertion yourself, such as:
  239. ```javascript
  240. const args = arg({ '--name': String });
  241. if (!args['--name']) throw new Error('missing required argument: --name');
  242. ```
  243. # License
  244. Released under the [MIT License](LICENSE.md).