项目作者: zeit

项目描述 :
简单的参数解析
高级语言: JavaScript
项目地址: git://github.com/zeit/arg.git
创建时间: 2017-08-20T00:38:19Z
项目社区:https://github.com/zeit/arg

开源协议:MIT License

下载


Arg

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

Installation

  1. npm install arg

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. const arg = require('arg');
  2. // `options` is an optional parameter
  3. const args = arg(
  4. spec,
  5. (options = { permissive: false, argv: process.argv.slice(2) })
  6. );

For example:

  1. $ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar
  1. // hello.js
  2. const arg = require('arg');
  3. const args = arg({
  4. // Types
  5. '--help': Boolean,
  6. '--version': Boolean,
  7. '--verbose': arg.COUNT, // Counts the number of times --verbose is passed
  8. '--port': Number, // --port <number> or --port=<number>
  9. '--name': String, // --name <string> or --name=<string>
  10. '--tag': [String], // --tag <string> or --tag=<string>
  11. // Aliases
  12. '-v': '--verbose',
  13. '-n': '--name', // -n <string>; result is stored in --name
  14. '--label': '--name' // --label <string> or --label=<string>;
  15. // result is stored in --name
  16. });
  17. console.log(args);
  18. /*
  19. {
  20. _: ["foo", "bar", "--foobar"],
  21. '--port': 1234,
  22. '--verbose': 4,
  23. '--name': "My name",
  24. '--tag': ["qux", "qix"]
  25. }
  26. */

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. const arg = require('arg');
  2. const argv = [
  3. '--foo',
  4. 'bar',
  5. '-ff',
  6. 'baz',
  7. '--foo',
  8. '--foo',
  9. 'qux',
  10. '-fff',
  11. 'qix'
  12. ];
  13. function myHandler(value, argName, previousValue) {
  14. /* `value` is always `true` */
  15. return 'na ' + (previousValue || 'batman!');
  16. }
  17. const args = arg(
  18. {
  19. '--foo': arg.flag(myHandler),
  20. '-f': '--foo'
  21. },
  22. {
  23. argv
  24. }
  25. );
  26. console.log(args);
  27. /*
  28. {
  29. _: ['bar', 'baz', 'qux', 'qix'],
  30. '--foo': 'na na na na na na na na batman!'
  31. }
  32. */

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. const arg = require('arg');
  2. const argv = ['-AAAA', '-BBBB'];
  3. const args = arg(
  4. {
  5. '-A': arg.COUNT,
  6. '-B': [Boolean]
  7. },
  8. {
  9. argv
  10. }
  11. );
  12. console.log(args);
  13. /*
  14. {
  15. _: [],
  16. '-A': 4,
  17. '-B': [true, true, true, true]
  18. }
  19. */

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. const args = arg(
  2. {
  3. '--foo': String
  4. },
  5. {
  6. argv: ['hello', '--foo', 'world']
  7. }
  8. );

results in:

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

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. const arg = require('arg');
  2. const argv = [
  3. '--foo',
  4. 'hello',
  5. '--qux',
  6. 'qix',
  7. '--bar',
  8. '12345',
  9. 'hello again'
  10. ];
  11. const args = arg(
  12. {
  13. '--foo': String,
  14. '--bar': Number
  15. },
  16. {
  17. argv,
  18. permissive: true
  19. }
  20. );

results in:

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

stopAtPositional

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

For example:

  1. const arg = require('arg');
  2. const argv = ['--foo', 'hello', '--bar'];
  3. const args = arg(
  4. {
  5. '--foo': Boolean,
  6. '--bar': Boolean
  7. },
  8. {
  9. argv,
  10. stopAtPositional: true
  11. }
  12. );

results in:

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

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. // cli.js
  2. try {
  3. require('arg')({ '--hi': String });
  4. } catch (err) {
  5. if (err.code === 'ARG_UNKNOWN_OPTION') {
  6. console.log(err.message);
  7. } else {
  8. throw err;
  9. }
  10. }
  1. node cli.js --extraneous true
  2. Unknown or unexpected option: --extraneous

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. const args = arg({ '--name': String });
  2. if (!args['--name']) throw new Error('missing required argument: --name');

License

Released under the MIT License.