Arg

Simple argument parsing

README

Arg


arg is an unopinionated, no-frills CLI argument parser.

Installation


  1. ``` sh
  2. npm install arg
  3. ```

Usage


arg() takes either 1 or 2 arguments:

1. Command line specification object (see below)
2. Parse options (_Optional_, defaults to {permissive: false, argv: process.argv.slice(2), stopAtPositional: false})

It returns an object with any values present on the command-line (missing options are thus
missing from the resulting object). Arg performs no validation/requirement checking - we
leave that up to the application.

All parameters that aren't consumed by options (commonly referred to as "extra" parameters)
are added to result._, which is _always_ an array (even if no extra parameters are passed,
in which case an empty array is returned).

  1. ``` js
  2. const arg = require('arg');

  3. // `options` is an optional parameter
  4. const args = arg(
  5. spec,
  6. (options = { permissive: false, argv: process.argv.slice(2) })
  7. );
  8. ```

For example:

  1. ```console
  2. $ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar
  3. ```

  1. ``` js
  2. // hello.js
  3. const arg = require('arg');

  4. const args = arg({
  5. // Types
  6. '--help': Boolean,
  7. '--version': Boolean,
  8. '--verbose': arg.COUNT, // Counts the number of times --verbose is passed
  9. '--port': Number, // --port or --port=
  10. '--name': String, // --name or --name=
  11. '--tag': [String], // --tag or --tag=

  12. // Aliases
  13. '-v': '--verbose',
  14. '-n': '--name', // -n ; result is stored in --name
  15. '--label': '--name' // --label or --label=;
  16. //     result is stored in --name
  17. });

  18. console.log(args);
  19. /*
  20. {
  21. _: ["foo", "bar", "--foobar"],
  22. '--port': 1234,
  23. '--verbose': 4,
  24. '--name': "My name",
  25. '--tag': ["qux", "qix"]
  26. }
  27. */
  28. ```

The values for each key=>value pair is either a type (function or [function]) or a string (indicating an alias).

- In the case of a function, the string value of the argument's value is passed to it,
  and the return value is used as the ultimate value.

- In the case of an array, the only element _must_ be a type function. Array types indicate
  that the argument may be passed multiple times, and as such the resulting value in the returned
  object is an array with all of the values that were passed using the specified flag.

- In the case of a string, an alias is established. If a flag is passed that matches the _key_,
  then the _value_ is substituted in its place.

Type functions are passed three arguments:

1. The parameter value (always a string)
2. The parameter name (e.g. --label)
3. The previous value for the destination (useful for reduce-like operations or for supporting -v multiple times, etc.)

This means the built-in String, Number, and Boolean type constructors "just work" as type functions.

Note that Boolean and [Boolean] have special treatment - an option argument is _not_ consumed or passed, but instead true is
returned. These options are called "flags".

For custom handlers that wish to behave as flags, you may pass the function through arg.flag():

  1. ``` js
  2. const arg = require('arg');

  3. const argv = [
  4. '--foo',
  5. 'bar',
  6. '-ff',
  7. 'baz',
  8. '--foo',
  9. '--foo',
  10. 'qux',
  11. '-fff',
  12. 'qix'
  13. ];

  14. function myHandler(value, argName, previousValue) {
  15. /* `value` is always `true` */
  16. return 'na ' + (previousValue || 'batman!');
  17. }

  18. const args = arg(
  19. {
  20.   '--foo': arg.flag(myHandler),
  21.   '-f': '--foo'
  22. },
  23. {
  24.   argv
  25. }
  26. );

  27. console.log(args);
  28. /*
  29. {
  30. _: ['bar', 'baz', 'qux', 'qix'],
  31. '--foo': 'na na na na na na na na batman!'
  32. }
  33. */
  34. ```

As well, arg supplies a helper argument handler called arg.COUNT, which equivalent to a [Boolean] argument's .length
property - effectively counting the number of times the boolean flag, denoted by the key, is passed on the command line..
For example, this is how you could implement ssh's multiple levels of verbosity (-vvvv being the most verbose).

  1. ``` js
  2. const arg = require('arg');

  3. const argv = ['-AAAA', '-BBBB'];

  4. const args = arg(
  5. {
  6.   '-A': arg.COUNT,
  7.   '-B': [Boolean]
  8. },
  9. {
  10.   argv
  11. }
  12. );

  13. console.log(args);
  14. /*
  15. {
  16. _: [],
  17. '-A': 4,
  18. '-B': [true, true, true, true]
  19. }
  20. */
  21. ```

Options


If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of arg().

argv


If you have already sliced or generated a number of raw arguments to be parsed (as opposed to letting arg
slice them from process.argv) you may specify them in the argv option.

For example:

  1. ``` js
  2. const args = arg(
  3. {
  4.   '--foo': String
  5. },
  6. {
  7.   argv: ['hello', '--foo', 'world']
  8. }
  9. );
  10. ```

results in:

  1. ``` js
  2. const args = {
  3. _: ['hello'],
  4. '--foo': 'world'
  5. };
  6. ```

permissive


When permissive set to true, arg will push any unknown arguments
onto the "extra" argument array (result._) instead of throwing an error about
an unknown flag.

For example:

  1. ``` js
  2. const arg = require('arg');

  3. const argv = [
  4. '--foo',
  5. 'hello',
  6. '--qux',
  7. 'qix',
  8. '--bar',
  9. '12345',
  10. 'hello again'
  11. ];

  12. const args = arg(
  13. {
  14.   '--foo': String,
  15.   '--bar': Number
  16. },
  17. {
  18.   argv,
  19.   permissive: true
  20. }
  21. );
  22. ```

results in:

  1. ``` js
  2. const args = {
  3. _: ['--qux', 'qix', 'hello again'],
  4. '--foo': 'hello',
  5. '--bar': 12345
  6. };
  7. ```

stopAtPositional


When stopAtPositional is set to true, arg will halt parsing at the first
positional argument.

For example:

  1. ``` js
  2. const arg = require('arg');

  3. const argv = ['--foo', 'hello', '--bar'];

  4. const args = arg(
  5. {
  6.   '--foo': Boolean,
  7.   '--bar': Boolean
  8. },
  9. {
  10.   argv,
  11.   stopAtPositional: true
  12. }
  13. );
  14. ```

results in:

  1. ``` js
  2. const args = {
  3. _: ['hello', '--bar'],
  4. '--foo': true
  5. };
  6. ```

Errors


Some errors that arg throws provide a .code property in order to aid in recovering from user error, or to
differentiate between user error and developer error (bug).

ARG_UNKNOWN_OPTION

If an unknown option (not defined in the spec object) is passed, an error with code ARG_UNKNOWN_OPTION will be thrown:

  1. ``` js
  2. // cli.js
  3. try {
  4. require('arg')({ '--hi': String });
  5. } catch (err) {
  6. if (err.code === 'ARG_UNKNOWN_OPTION') {
  7.   console.log(err.message);
  8. } else {
  9.   throw err;
  10. }
  11. }
  12. ```

  1. ``` sh
  2. node cli.js --extraneous true
  3. Unknown or unexpected option: --extraneous
  4. ```

FAQ


A few questions and answers that have been asked before:

How do I require an argument with arg?


Do the assertion yourself, such as:

  1. ``` js
  2. const args = arg({ '--name': String });

  3. if (!args['--name']) throw new Error('missing required argument: --name');
  4. ```

License


Released under the MIT License.