parseArgs
Polyfill of util.parseArgs()
util.parseArgs([config])
Stability: 1 - Experimental
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.
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f'
},
bar: {
type: 'string'
}
};
const {
values,
positionals
} = parseArgs({ args, options });
console.log(values, positionals);
const { parseArgs } = require('node:util');
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f'
},
bar: {
type: 'string'
}
};
const {
values,
positionals
} = parseArgs({ args, options });
console.log(values, positionals);
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:
- all tokens
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]
.
- option tokens
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
.
- positional tokens
value
{string} The value of the positional argument in args (i.e. args[index]
).
- option-terminator token
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.
import { parseArgs } from 'node:util';
const options = {
'color': { type: 'boolean' },
'no-color': { type: 'boolean' },
'logfile': { type: 'string' },
'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
tokens
.filter((token) => token.kind === 'option')
.forEach((token) => {
if (token.name.startsWith('no-')) {
const positiveName = token.name.slice(3);
values[positiveName] = false;
delete values[token.name];
} else {
values[token.name] = token.value ?? true;
}
});
const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
const { parseArgs } = require('node:util');
const options = {
'color': { type: 'boolean' },
'no-color': { type: 'boolean' },
'logfile': { type: 'string' },
'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
tokens
.filter((token) => token.kind === 'option')
.forEach((token) => {
if (token.name.startsWith('no-')) {
const positiveName = token.name.slice(3);
values[positiveName] = false;
delete values[token.name];
} else {
values[token.name] = token.value ?? true;
}
});
const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
Example usage showing negated options, and when an option is used
multiple ways then last one wins.
$ node negate.js
{ logfile: 'default.log', color: undefined }
$ node negate.js --no-logfile --no-color
{ logfile: false, color: false }
$ node negate.js --logfile=test.log --color
{ logfile: 'test.log', color: true }
$ node negate.js --no-logfile --logfile=test.log --color --no-color
{ logfile: 'test.log', color: false }
Table of Contents
Scope
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.
Version Matchups
🚀 Getting Started
-
Install dependencies.
npm install
-
Open the index.js file and start editing!
-
Test your code by calling parseArgs through our test file
npm test
🙌 Contributing
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
Proposal
Note: This can be moved forward independently of the util.parseArgs()
proposal/work.
Implementation:
process.mainArgs = process.argv.slice(process._exec ? 1 : 2)
📃 Examples
const { parseArgs } = require('@pkgjs/parseargs');
const { parseArgs } = require('@pkgjs/parseargs');
const options = {
foo: { type: 'string'},
bar: { type: 'boolean' },
};
const args = ['--foo=a', '--bar'];
const { values, positionals } = parseArgs({ args, options });
const { parseArgs } = require('@pkgjs/parseargs');
const options = {
foo: {
type: 'string',
multiple: true,
},
};
const args = ['--foo=a', '--foo', 'b'];
const { values, positionals } = parseArgs({ args, options });
const { parseArgs } = require('@pkgjs/parseargs');
const options = {
foo: {
short: 'f',
type: 'boolean'
},
};
const args = ['-f', 'b'];
const { values, positionals } = parseArgs({ args, options, allowPositionals: true });
const { parseArgs } = require('@pkgjs/parseargs');
const options = {};
const args = ['-f', '--foo=a', '--bar', 'b'];
const { values, positionals } = parseArgs({ strict: false, args, options, allowPositionals: true });
F.A.Qs
- Is
cmd --foo=bar baz
the same as cmd baz --foo=bar
?
- Does the parser execute a function?
- Does the parser execute one of several functions, depending on input?
- Can subcommands take options that are distinct from the main command?
- Does it output generated help when no options match?
- Does it generated short usage? Like:
usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]
- no (no usage/help at all)
- Does the user provide the long usage text? For each option? For the whole command?
- Do subcommands (if implemented) have their own usage output?
- Does usage print if the user runs
cmd --help
?
- Does it set
process.exitCode
?
- Does usage print to stderr or stdout?
- Does it check types? (Say, specify that an option is a boolean, number, etc.)
- Can an option have more than one type? (string or false, for example)
- Can the user define a type? (Say,
type: path
to call path.resolve()
on the argument.)
- Does a
--foo=0o22
mean 0, 22, 18, or "0o22"?
- Does it coerce types?
- Does
--no-foo
coerce to --foo=false
? For all options? Only boolean options?
- no, it sets
{values:{'no-foo': true}}
- Is
--foo
the same as --foo=true
? Only for known booleans? Only at the end?
- no, they are not the same. There is no special handling of
true
as a value so it is just another string.
- Does it read environment variables? Ie, is
FOO=1 cmd
the same as cmd --foo=1
?
- Do unknown arguments raise an error? Are they parsed? Are they treated as positional arguments?
- no, they are parsed, not treated as positionals
- Does
--
signal the end of options?
- Is
--
included as a positional?
- Is
program -- foo
the same as program foo
?
- yes, both store
{positionals:['foo']}
- Does the API specify whether a
--
was present/relevant?
- Is
-bar
the same as --bar
?
- Is
---foo
the same as --foo
?
- no
- the first is a long option named
'-foo'
- the second is a long option named
'foo'
- Is
-
a positional? ie, bash some-test.sh | tap -
Links & Resources