CLI Args Parser With Subcommands

Parse CLI arguments with subcommands flags and positional args using a declarative spec for consistent tooling.

JavascriptCli Tooling

Code

javascriptsnippet
1 line
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 early throw when 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

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.