A wrapper for node’s built-in util.parseArgs with helpful features added.
#!/usr/bin/env node
import pargs from 'pargs';
const {
help,
positionals,
values,
errors, // a mutable string array; push to it and pargs will include your error messages.
name, // if subcommands are used
tokens,
} = await pargs(import.meta.filename, options);
// do extra validation here
await help(); // to handle `--help` and print the help text if needed, or to print errors and exitHelp text is automatically read from a help.txt file adjacent to import.meta.filename, when one is present.
When no help.txt file exists, help text is generated automatically from the provided config - the usage line, options (with their types, choices, defaults, and short flags), subcommands, and positional argument requirements. A help.txt file, when present, always takes precedence over the generated text.
The program name in the generated usage line comes from the nearest package.json (the bin entry that points at the entrypoint, falling back to the unscoped package name, then to the file’s basename).
The following config fields exist solely to enrich generated help; they are ignored by util.parseArgs:
options[name].description: a string describing the option.options[name].placeholder: the value placeholder shown for a non-boolean option (eg,placeholder: 'MM/DD/YYYY'renders--before <MM/DD/YYYY>instead of<string>).options[name].group: a heading to group the option under; ungrouped options appear first underOptions, and--helpis always listed there.options[name].defaultDescription: a string shown as the default in place of the actualdefaultvalue - useful to mask a secret, or to show an env-derived default symbolically (eg,$HOME/.cacherather than the resolved path).positionals: an array of{ name, description?, rest? }, used to name positionals in the usage line (<name>when required perminPositionals, else[name];rest: truemakes it variadic) and to render anArguments:section.description(on a config or subcommand): either a string (used as the summary), or an object{ summary?, examples?, sections? }, whereexamplesis an array of strings or{ command, description? }, andsectionsis an array of{ title, body }for free-form blocks (eg,Behavior,Exit codes).
Option defaults are shown as (default: …), except that a boolean option’s default: false is omitted (it is the implicit default; default: true is still shown). Array defaults render as [a, b] / [].
await an invocation of the help function returned from the pargs call to handle --help and print the help text if needed, or to print errors and exit.
--version is provided automatically: the same await help() call handles it, printing the version field from the nearest package.json and exiting.
Unlike help, version is not reserved - if you define your own version option, yours (and your own handling) is used instead, and the built-in one is not added.
See the node.js parseArgs documentation for some context.
strict: can not be set tofalse- strictness all the way.allowNegative: can not be set tofalse.negation:'exclusive'(the default) reports an error when both--xand--no-xappear in the same invocation;'last-wins'suppresses that error and leaves the parsed value alone, so the last occurrence wins for a scalar boolean, and every occurrence is collected for amultipleone. May be set at the root, or per-option (options[name].negation) to override the root; it does not inherit into subcommands. The reserved--helpand--versionare unaffected ---no-helpis always an unknown option.args: when omitted, pargs usesprocess.argv, with the node binary and the entrypoint filtered out. When provided, it is the argument list, used verbatim - nothing is filtered out of it, each element is coerced withString, and a non-array throws. An explicitargsalso governs subcommand anddefaultCommandrouting, and suppresses theprocess.argvmutation that subcommand routing otherwise performs. A subcommand's ownargs, if it declares one, is overridden by the parent's routing.options.type: in addition to'boolean'and'string':'enum': when provided, achoicesstring array is also required. The value is validated only when one is present - an option that was not passed and has nodefaultis not an error. Withmultiple, each element is validated individually.'number': validates the value is a finite number and coerces it from a string.'integer': validates the value is a finite integer and coerces it from a string.
partialValues: whentrue, a fatal parse error (an unknown option, a missing option argument) returns whatever else parsed cleanly instead of an emptyvalues. Only declared options survive, and only when the loosely-parsed value still matches the declared type;enumchoices andnumber/integercoercion are applied as usual, and anything that fails is dropped.errorsstill holds only the single fatal error,positionalscome from the loose reparse and so do not re-apply the configured positional policy, and an option with adefaultmay be missing - sovaluesis a partial of its usual type. Defaults tofalse, and does not inherit into subcommands.allowPositionals: in addition to a boolean, or an integer representing the maximum number of allowed positional arguments.minPositionals: an integer representing the minimum required number of positional arguments.subcommands: if provided, must be an object. Keys are the subcommand names (eg, innpm ls,lsis the subcommand), and values are the configuration options for each subcommand - as if they were a top-level invocation.defaultCommand: only allowed alongsidesubcommands; must be the name of one of them. When the first argument is not a recognized subcommand (including when it is a flag, or absent entirely), the full argument list is parsed against this command instead of erroring withunknown command. This enables a bare default form (eg,vers <input>) to coexist with named subcommands.--help/--versionstill apply at the level invoked: a root-level--help(no recognized subcommand) shows the root help (the command list), not the default command's help.
``
npm install --save pargsMIT
Thanks to @ibakaidov for donating the pargs package name!
