Gathering detailed insights and metrics for @pkgjs/parseargs
Gathering detailed insights and metrics for @pkgjs/parseargs
Gathering detailed insights and metrics for @pkgjs/parseargs
Gathering detailed insights and metrics for @pkgjs/parseargs
@types/pkgjs__parseargs
TypeScript definitions for @pkgjs/parseargs
@pkgjs/nv
A tool for resolving node versions from common aliases
camelcase-keys
Convert object keys to camel case
@pkgjs/support
Package support information (see: https://github.com/nodejs/package-maintenance/pull/220)
npm install @pkgjs/parseargs
99.9
Supply Chain
99.5
Quality
75.8
Maintenance
100
Vulnerability
99.6
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
123 Stars
86 Commits
10 Forks
17 Watching
2 Branches
30 Contributors
Updated on 25 Nov 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-6.6%
4,548,467
Compared to previous day
Last week
1.7%
26,168,576
Compared to previous week
Last month
6.9%
110,585,261
Compared to previous month
Last year
346.3%
994,171,593
Compared to previous year
4
Polyfill of util.parseArgs()
util.parseArgs([config])
Stability: 1 - Experimental
config
{Object} Used to provide arguments for parsing and to configure
the parser. config
supports the following properties:
args
{string[]} array of argument strings. Default: process.argv
with execPath
and filename
removed.options
{Object} Used to describe arguments known to the parser.
Keys of options
are the long names of options and values are an
{Object} accepting the following properties:
type
{string} Type of argument, which must be either boolean
or string
.multiple
{boolean} Whether this option can be provided multiple
times. If true
, all values will be collected in an array. If
false
, values for the option are last-wins. Default: false
.short
{string} A single character alias for the option.default
{string | boolean | string[] | boolean[]} The default option
value when it is not set by args. It must be of the same type as the
the type
property. When multiple
is true
, it must be an array.strict
{boolean} Should an error be thrown when unknown arguments
are encountered, or when arguments are passed that do not match the
type
configured in options
.
Default: true
.allowPositionals
{boolean} Whether this command accepts positional
arguments.
Default: false
if strict
is true
, otherwise true
.tokens
{boolean} Return the parsed tokens. This is useful for extending
the built-in behavior, from adding additional checks through to reprocessing
the tokens in different ways.
Default: false
.Returns: {Object} The parsed command line arguments:
values
{Object} A mapping of parsed option names with their {string}
or {boolean} values.positionals
{string[]} Positional arguments.tokens
{Object[] | undefined} See parseArgs tokens
section. Only returned if config
includes tokens: true
.Provides a higher level API for command-line argument parsing than interacting
with process.argv
directly. Takes a specification for the expected arguments
and returns a structured object with the parsed options and positionals.
1import { parseArgs } from 'node:util'; 2const args = ['-f', '--bar', 'b']; 3const options = { 4 foo: { 5 type: 'boolean', 6 short: 'f' 7 }, 8 bar: { 9 type: 'string' 10 } 11}; 12const { 13 values, 14 positionals 15} = parseArgs({ args, options }); 16console.log(values, positionals); 17// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
1const { parseArgs } = require('node:util'); 2const args = ['-f', '--bar', 'b']; 3const options = { 4 foo: { 5 type: 'boolean', 6 short: 'f' 7 }, 8 bar: { 9 type: 'string' 10 } 11}; 12const { 13 values, 14 positionals 15} = parseArgs({ args, options }); 16console.log(values, positionals); 17// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
util.parseArgs
is experimental and behavior may change. Join the
conversation in pkgjs/parseargs to contribute to the design.
parseArgs
tokens
Detailed parse information is available for adding custom behaviours by
specifying tokens: true
in the configuration.
The returned tokens have properties describing:
kind
{string} One of 'option', 'positional', or 'option-terminator'.index
{number} Index of element in args
containing token. So the
source argument for a token is args[token.index]
.name
{string} Long name of option.rawName
{string} How option used in args, like -f
of --foo
.value
{string | undefined} Option value specified in args.
Undefined for boolean options.inlineValue
{boolean | undefined} Whether option value specified inline,
like --foo=bar
.value
{string} The value of the positional argument in args (i.e. args[index]
).The returned tokens are in the order encountered in the input args. Options
that appear more than once in args produce a token for each use. Short option
groups like -xy
expand to a token for each option. So -xxx
produces
three tokens.
For example to use the returned tokens to add support for a negated option
like --no-color
, the tokens can be reprocessed to change the value stored
for the negated option.
1import { parseArgs } from 'node:util'; 2 3const options = { 4 'color': { type: 'boolean' }, 5 'no-color': { type: 'boolean' }, 6 'logfile': { type: 'string' }, 7 'no-logfile': { type: 'boolean' }, 8}; 9const { values, tokens } = parseArgs({ options, tokens: true }); 10 11// Reprocess the option tokens and overwrite the returned values. 12tokens 13 .filter((token) => token.kind === 'option') 14 .forEach((token) => { 15 if (token.name.startsWith('no-')) { 16 // Store foo:false for --no-foo 17 const positiveName = token.name.slice(3); 18 values[positiveName] = false; 19 delete values[token.name]; 20 } else { 21 // Resave value so last one wins if both --foo and --no-foo. 22 values[token.name] = token.value ?? true; 23 } 24 }); 25 26const color = values.color; 27const logfile = values.logfile ?? 'default.log'; 28 29console.log({ logfile, color });
1const { parseArgs } = require('node:util'); 2 3const options = { 4 'color': { type: 'boolean' }, 5 'no-color': { type: 'boolean' }, 6 'logfile': { type: 'string' }, 7 'no-logfile': { type: 'boolean' }, 8}; 9const { values, tokens } = parseArgs({ options, tokens: true }); 10 11// Reprocess the option tokens and overwrite the returned values. 12tokens 13 .filter((token) => token.kind === 'option') 14 .forEach((token) => { 15 if (token.name.startsWith('no-')) { 16 // Store foo:false for --no-foo 17 const positiveName = token.name.slice(3); 18 values[positiveName] = false; 19 delete values[token.name]; 20 } else { 21 // Resave value so last one wins if both --foo and --no-foo. 22 values[token.name] = token.value ?? true; 23 } 24 }); 25 26const color = values.color; 27const logfile = values.logfile ?? 'default.log'; 28 29console.log({ logfile, color });
Example usage showing negated options, and when an option is used multiple ways then last one wins.
1$ node negate.js 2{ logfile: 'default.log', color: undefined } 3$ node negate.js --no-logfile --no-color 4{ logfile: false, color: false } 5$ node negate.js --logfile=test.log --color 6{ logfile: 'test.log', color: true } 7$ node negate.js --no-logfile --logfile=test.log --color --no-color 8{ logfile: 'test.log', color: false }
util.parseArgs([config])
process.mainArgs
Proposal
It is already possible to build great arg parsing modules on top of what Node.js provides; the prickly API is abstracted away by these modules. Thus, process.parseArgs() is not necessarily intended for library authors; it is intended for developers of simple CLI tools, ad-hoc scripts, deployed Node.js applications, and learning materials.
It is exceedingly difficult to provide an API which would both be friendly to these Node.js users while being extensible enough for libraries to build upon. We chose to prioritize these use cases because these are currently not well-served by Node.js' API.
Node.js | @pkgjs/parseArgs | Changes |
---|---|---|
v18.11.0 | 0.11.0 | Add support for default values in input config . |
v16.17.0, v18.7.0 | 0.10.0 | Add support for returning detailed parse information using tokens in input config and returned properties. |
v18.3.0 | v0.9.1 |
Install dependencies.
1npm install
Open the index.js file and start editing!
Test your code by calling parseArgs through our test file
1npm test
Any person who wants to contribute to the initiative is welcome! Please first read the Contributing Guide
Additionally, reading the Examples w/ Output
section of this document will be the best way to familiarize yourself with the target expected behavior for parseArgs() once it is fully implemented.
This package was implemented using tape as its test harness.
process.mainArgs
ProposalNote: This can be moved forward independently of the
util.parseArgs()
proposal/work.
1process.mainArgs = process.argv.slice(process._exec ? 1 : 2)
1const { parseArgs } = require('@pkgjs/parseargs');
1const { parseArgs } = require('@pkgjs/parseargs'); 2// specify the options that may be used 3const options = { 4 foo: { type: 'string'}, 5 bar: { type: 'boolean' }, 6}; 7const args = ['--foo=a', '--bar']; 8const { values, positionals } = parseArgs({ args, options }); 9// values = { foo: 'a', bar: true } 10// positionals = []
1const { parseArgs } = require('@pkgjs/parseargs'); 2// type:string & multiple 3const options = { 4 foo: { 5 type: 'string', 6 multiple: true, 7 }, 8}; 9const args = ['--foo=a', '--foo', 'b']; 10const { values, positionals } = parseArgs({ args, options }); 11// values = { foo: [ 'a', 'b' ] } 12// positionals = []
1const { parseArgs } = require('@pkgjs/parseargs'); 2// shorts 3const options = { 4 foo: { 5 short: 'f', 6 type: 'boolean' 7 }, 8}; 9const args = ['-f', 'b']; 10const { values, positionals } = parseArgs({ args, options, allowPositionals: true }); 11// values = { foo: true } 12// positionals = ['b']
1const { parseArgs } = require('@pkgjs/parseargs'); 2// unconfigured 3const options = {}; 4const args = ['-f', '--foo=a', '--bar', 'b']; 5const { values, positionals } = parseArgs({ strict: false, args, options, allowPositionals: true }); 6// values = { f: true, foo: 'a', bar: true } 7// positionals = ['b']
cmd --foo=bar baz
the same as cmd baz --foo=bar
?
usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]
cmd --help
?
process.exitCode
?
type: path
to call path.resolve()
on the argument.)
--foo=0o22
mean 0, 22, 18, or "0o22"?
"0o22"
--no-foo
coerce to --foo=false
? For all options? Only boolean options?
{values:{'no-foo': true}}
--foo
the same as --foo=true
? Only for known booleans? Only at the end?
true
as a value so it is just another string.FOO=1 cmd
the same as cmd --foo=1
?
--
signal the end of options?
--
included as a positional?
program -- foo
the same as program foo
?
{positionals:['foo']}
--
was present/relevant?
-bar
the same as --bar
?
-bar
is a short option or options, with expansion logic that follows the
Utility Syntax Guidelines in POSIX.1-2017. -bar
expands to -b
, -a
, -r
.---foo
the same as --foo
?
'-foo'
'foo'
-
a positional? ie, bash some-test.sh | tap -
No vulnerabilities found.
No security vulnerabilities found.