Polyfill of proposal for util.parseArgs()
Stability: 1 - Experimental
-
config{Object} Used to provide arguments for parsing and to configure the parser.configsupports the following properties:args{string[]} array of argument strings. Default:process.argvwithexecPathandfilenameremoved.options{Object} Used to describe arguments known to the parser. Keys ofoptionsare the long names of options and values are an {Object} accepting the following properties:type{string} Type of argument, which must be eitherbooleanorstring.multiple{boolean} Whether this option can be provided multiple times. Iftrue, all values will be collected in an array. Iffalse, values for the option are last-wins. Default:false.short{string} A single character alias for the option.
strict: {boolean} Should an error be thrown when unknown arguments are encountered, or when arguments are passed that do not match thetypeconfigured inoptions. Default:true.allowPositionals: {boolean} Whether this command accepts positional arguments. Default:falseifstrictistrue, otherwisetrue.
-
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.
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);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []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);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []ssutil.parseArgs is experimental and behavior may change. Join the
conversation in pkgjs/parseargs to contribute to the design.
util.parseArgs([config])- π Getting Started
- π Contributing
- π‘
process.mainArgsProposal - π‘
util.parseArgs([config])Proposal - π Examples
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.
-
Install dependencies.
npm install
-
Open the index.js file and start editing!
-
Test your code by calling parseArgs through our test file
npm 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.
Note: This can be moved forward independently of the
util.parseArgs()proposal/work.
process.mainArgs = process.argv.slice(process._exec ? 1 : 2)config{Object} (Optional) Theconfigparameter is an object supporting the following properties:args{string[]} (Optional) Array of argument strings; defaults toprocess.mainArgsoptions{Object} (Optional) An object describing the known options to look for inargs;optionskeys are the long names of the known options, and the values are objects with the following properties:type{'string'|'boolean'} (Required) Type of known optionmultiple{boolean} (Optional) If true, when appearing one or more times inargs, results are collected in anArrayshort{string} (Optional) A single character alias for an option; When appearing one or more times inargs; Respects themultipleconfiguration
strict{Boolean} (Optional) ABooleanfor whether or not to throw an error when unknown options are encountered,type:'string'options are missing an options-argument, ortype:'boolean'options are passed an options-argument; defaults totrueallowPositionals{Boolean} (Optional) Whether this command accepts positional arguments. Defaultsfalseifstrictistrue, otherwise defaults totrue.
- Returns: {Object} An object having properties:
values{Object}, key:value for each option found. Value is a string for string options, ortruefor boolean options, or an array (of strings or booleans) for options configured asmultiple:true.positionals{string[]}, containing [Positionals][]
const { parseArgs } = require('@pkgjs/parseargs');const { parseArgs } = require('@pkgjs/parseargs');
// specify the options that may be used
const options = {
foo: { type: 'string'},
bar: { type: 'boolean' },
};
const args = ['--foo=a', '--bar'];
const { values, positionals } = parseArgs({ args, options });
// values = { foo: 'a', bar: true }
// positionals = []const { parseArgs } = require('@pkgjs/parseargs');
// type:string & multiple
const options = {
foo: {
type: 'string',
multiple: true,
},
};
const args = ['--foo=a', '--foo', 'b'];
const { values, positionals } = parseArgs({ args, options });
// values = { foo: [ 'a', 'b' ] }
// positionals = []const { parseArgs } = require('@pkgjs/parseargs');
// shorts
const options = {
foo: {
short: 'f',
type: 'boolean'
},
};
const args = ['-f', 'b'];
const { values, positionals } = parseArgs({ args, options, allowPositionals: true });
// values = { foo: true }
// positionals = ['b']const { parseArgs } = require('@pkgjs/parseargs');
// unconfigured
const options = {};
const args = ['-f', '--foo=a', '--bar', 'b'];
const { values, positionals } = parseArgs({ strict: false, args, options, allowPositionals: true });
// values = { f: true, foo: 'a', bar: true }
// positionals = ['b']- Is
cmd --foo=bar bazthe same ascmd baz --foo=bar?- yes
- Does the parser execute a function?
- no
- Does the parser execute one of several functions, depending on input?
- no
- Can subcommands take options that are distinct from the main command?
- no
- Does it output generated help when no options match?
- no
- 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?
- no
- Do subcommands (if implemented) have their own usage output?
- no
- Does usage print if the user runs
cmd --help?- no
- Does it set
process.exitCode?- no
- Does usage print to stderr or stdout?
- N/A
- Does it check types? (Say, specify that an option is a boolean, number, etc.)
- no
- Can an option have more than one type? (string or false, for example)
- no
- Can the user define a type? (Say,
type: pathto callpath.resolve()on the argument.)- no
- Does a
--foo=0o22mean 0, 22, 18, or "0o22"?"0o22"
- Does it coerce types?
- no
- Does
--no-foocoerce to--foo=false? For all options? Only boolean options?- no, it sets
{values:{'no-foo': true}}
- no, it sets
- Is
--foothe same as--foo=true? Only for known booleans? Only at the end?- no, they are not the same. There is no special handling of
trueas a value so it is just another string.
- no, they are not the same. There is no special handling of
- Does it read environment variables? Ie, is
FOO=1 cmdthe same ascmd --foo=1?- no
- 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?- yes
- Is
--included as a positional?- no
- Is
program -- foothe same asprogram foo?- yes, both store
{positionals:['foo']}
- yes, both store
- Does the API specify whether a
--was present/relevant?- no
- Is
-barthe same as--bar?- no,
-baris a short option or options, with expansion logic that follows the Utility Syntax Guidelines in POSIX.1-2017.-barexpands to-b,-a,-r.
- no,
- Is
---foothe 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 -- yes