Installations
npm install arg
Developer
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
16.13.1
NPM Version
8.1.2
Statistics
1,243 Stars
63 Commits
53 Forks
56 Watching
7 Branches
85 Contributors
Updated on 27 Nov 2024
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
4,355,068,927
Last day
-8.2%
6,636,112
Compared to previous day
Last week
3%
39,102,022
Compared to previous week
Last month
-23.6%
159,212,922
Compared to previous month
Last year
31.9%
1,609,144,942
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Arg
arg
is an unopinionated, no-frills CLI argument parser.
Installation
1npm install arg
Usage
arg()
takes either 1 or 2 arguments:
- Command line specification object (see below)
- 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).
1const arg = require('arg'); 2 3// `options` is an optional parameter 4const args = arg( 5 spec, 6 (options = { permissive: false, argv: process.argv.slice(2) }) 7);
For example:
1$ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar
1// hello.js 2const arg = require('arg'); 3 4const 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 <number> or --port=<number> 10 '--name': String, // --name <string> or --name=<string> 11 '--tag': [String], // --tag <string> or --tag=<string> 12 13 // Aliases 14 '-v': '--verbose', 15 '-n': '--name', // -n <string>; result is stored in --name 16 '--label': '--name' // --label <string> or --label=<string>; 17 // result is stored in --name 18}); 19 20console.log(args); 21/* 22{ 23 _: ["foo", "bar", "--foobar"], 24 '--port': 1234, 25 '--verbose': 4, 26 '--name': "My name", 27 '--tag': ["qux", "qix"] 28} 29*/
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:
- The parameter value (always a string)
- The parameter name (e.g.
--label
) - 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()
:
1const arg = require('arg'); 2 3const argv = [ 4 '--foo', 5 'bar', 6 '-ff', 7 'baz', 8 '--foo', 9 '--foo', 10 'qux', 11 '-fff', 12 'qix' 13]; 14 15function myHandler(value, argName, previousValue) { 16 /* `value` is always `true` */ 17 return 'na ' + (previousValue || 'batman!'); 18} 19 20const args = arg( 21 { 22 '--foo': arg.flag(myHandler), 23 '-f': '--foo' 24 }, 25 { 26 argv 27 } 28); 29 30console.log(args); 31/* 32{ 33 _: ['bar', 'baz', 'qux', 'qix'], 34 '--foo': 'na na na na na na na na batman!' 35} 36*/
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).
1const arg = require('arg'); 2 3const argv = ['-AAAA', '-BBBB']; 4 5const args = arg( 6 { 7 '-A': arg.COUNT, 8 '-B': [Boolean] 9 }, 10 { 11 argv 12 } 13); 14 15console.log(args); 16/* 17{ 18 _: [], 19 '-A': 4, 20 '-B': [true, true, true, true] 21} 22*/
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:
1const args = arg( 2 { 3 '--foo': String 4 }, 5 { 6 argv: ['hello', '--foo', 'world'] 7 } 8);
results in:
1const 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:
1const arg = require('arg'); 2 3const argv = [ 4 '--foo', 5 'hello', 6 '--qux', 7 'qix', 8 '--bar', 9 '12345', 10 'hello again' 11]; 12 13const args = arg( 14 { 15 '--foo': String, 16 '--bar': Number 17 }, 18 { 19 argv, 20 permissive: true 21 } 22);
results in:
1const 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:
1const arg = require('arg'); 2 3const argv = ['--foo', 'hello', '--bar']; 4 5const args = arg( 6 { 7 '--foo': Boolean, 8 '--bar': Boolean 9 }, 10 { 11 argv, 12 stopAtPositional: true 13 } 14);
results in:
1const 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 2try { 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}
1node cli.js --extraneous true 2Unknown 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:
1const args = arg({ '--name': String }); 2 3if (!args['--name']) throw new Error('missing required argument: --name');
License
Released under the MIT License.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: MIT License: LICENSE.md:0
Reason
security policy file detected
Details
- Info: security policy file detected: github.com/vercel/.github/SECURITY.md:1
- Info: Found linked content: github.com/vercel/.github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/vercel/.github/SECURITY.md:1
- Info: Found text in security policy: github.com/vercel/.github/SECURITY.md:1
Reason
Found 13/29 approved changesets -- score normalized to 4
Reason
9 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-4q6p-r6v2-jvc5
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/vercel/arg/ci.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/vercel/arg/ci.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/ci.yml:21
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 15 are checked with a SAST tool
Score
3.6
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to arg
@types/npm-package-arg
TypeScript definitions for npm-package-arg
argle
Convenient arg-shifting to make optional parameters nicer
mixin-object
Mixin the own and inherited properties of other objects onto the first object. Pass an empty object as the first arg to shallow clone.
registry-info
Get registry info (url, auth token, headers) from an arg