CLI Args Parser With Subcommands
Parse CLI arguments with subcommands flags and positional args using a declarative spec for consistent tooling.
Code
export function cliParser(spec){function parse(argv){const[subcommand,...rest]=argv;if(!spec[subcommand])throw new Error('unknown subcommand: '+subcommand);const cmdSpec=spec[subcommand];const args={};const positional=[];let i=0;while(i<rest.length){const arg=rest[i];if(arg.startsWith('--')){const key=arg.slice(2);const val=rest[i+1]?.startsWith('--')?true:rest[++i];args[key]=cmdSpec.flags?.[key]?.type==='number'?Number(val):val;}else positional.push(arg);i++;}return{subcommand,args,positional};}return{parse};}What the code does
The working surface is the functions cliParser and parse — everything else is wiring.
A guard precedes the Error: bad state stops the flow there instead of continuing.
The result comes back as an object carrying subcommand, args.
Watch out for
- The guard
!spec[subcommand]short-circuits the flow with an earlythrowwhen its condition holds.
Where the applying happens
The primary signature is export function cliParser(spec)
cliParser is what another module would consume; nothing else here is load-bearing for callers.
The call returns subcommand, args — destructure what you need at the call site.
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What happens if the preconditions do not hold?
- The code throws `Error` — the guard `!spec[subcommand]` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `cliParser`, `parse` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.