Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
/argPublic

Simple argument parsing

License

NotificationsYou must be signed in to change notification settings

vercel/arg

Repository files navigation

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

Installation

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 thusmissing from the resulting object). Arg performs no validation/requirement checking - weleave that up to the application.

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

constarg=require('arg');// `options` is an optional parameterconstargs=arg(spec,(options={permissive:false,argv:process.argv.slice(2)}));

For example:

$node ./hello.js --verbose -vvv --port=1234 -n'My name' foo bar --tag qux --tag=qix -- --foobar
// hello.jsconstarg=require('arg');constargs=arg({// Types'--help':Boolean,'--version':Boolean,'--verbose':arg.COUNT,// Counts the number of times --verbose is passed'--port':Number,// --port <number> or --port=<number>'--name':String,// --name <string> or --name=<string>'--tag':[String],// --tag <string> or --tag=<string>// Aliases'-v':'--verbose','-n':'--name',// -n <string>; result is stored in --name'--label':'--name'// --label <string> or --label=<string>;//     result is stored in --name});console.log(args);/*{_: ["foo", "bar", "--foobar"],'--port': 1234,'--verbose': 4,'--name': "My name",'--tag': ["qux", "qix"]}*/

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 elementmust be a type function. Array types indicatethat the argument may be passed multiple times, and as such the resulting value in the returnedobject 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 thekey,then thevalue 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-inString,Number, andBoolean type constructors "just work" as type functions.

Note thatBoolean and[Boolean] have special treatment - an option argument isnot consumed or passed, but insteadtrue isreturned. These options are called "flags".

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

constarg=require('arg');constargv=['--foo','bar','-ff','baz','--foo','--foo','qux','-fff','qix'];functionmyHandler(value,argName,previousValue){/* `value` is always `true` */return'na '+(previousValue||'batman!');}constargs=arg({'--foo':arg.flag(myHandler),'-f':'--foo'},{argv});console.log(args);/*{_: ['bar', 'baz', 'qux', 'qix'],'--foo': 'na na na na na na na na batman!'}*/

As well,arg supplies a helper argument handler calledarg.COUNT, which equivalent to a[Boolean] argument's.lengthproperty - 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 implementssh's multiple levels of verbosity (-vvvv being the most verbose).

constarg=require('arg');constargv=['-AAAA','-BBBB'];constargs=arg({'-A':arg.COUNT,'-B':[Boolean]},{argv});console.log(args);/*{_: [],'-A': 4,'-B': [true, true, true, true]}*/

Options

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

argv

If you have already sliced or generated a number of raw arguments to be parsed (as opposed to lettingargslice them fromprocess.argv) you may specify them in theargv option.

For example:

constargs=arg({'--foo':String},{argv:['hello','--foo','world']});

results in:

constargs={_:['hello'],'--foo':'world'};

permissive

Whenpermissive set totrue,arg will push any unknown argumentsonto the "extra" argument array (result._) instead of throwing an error aboutan unknown flag.

For example:

constarg=require('arg');constargv=['--foo','hello','--qux','qix','--bar','12345','hello again'];constargs=arg({'--foo':String,'--bar':Number},{argv,permissive:true});

results in:

constargs={_:['--qux','qix','hello again'],'--foo':'hello','--bar':12345};

stopAtPositional

WhenstopAtPositional is set totrue,arg will halt parsing at the firstpositional argument.

For example:

constarg=require('arg');constargv=['--foo','hello','--bar'];constargs=arg({'--foo':Boolean,'--bar':Boolean},{argv,stopAtPositional:true});

results in:

constargs={_:['hello','--bar'],'--foo':true};

Errors

Some errors thatarg throws provide a.code property in order to aid in recovering from user error, or todifferentiate 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 codeARG_UNKNOWN_OPTION will be thrown:

// cli.jstry{require('arg')({'--hi':String});}catch(err){if(err.code==='ARG_UNKNOWN_OPTION'){console.log(err.message);}else{throwerr;}}
node cli.js --extraneoustrueUnknown or unexpected option: --extraneous

FAQ

A few questions and answers that have been asked before:

How do I require an argument witharg?

Do the assertion yourself, such as:

constargs=arg({'--name':String});if(!args['--name'])thrownewError('missing required argument: --name');

License

Released under theMIT License.


[8]ページ先頭

©2009-2025 Movatter.jp