Parse subcommands with parseArgs
Build a git-style CLI with subcommands in Node.js 24 by reading the first argument as the command and running util.parseArgs with that command's options.
util.parseArgs parses one flat set of options, with no idea of commands such as deploy or rollback. Take the first argument as the command, then parse the rest with that command's own options.
import { parseArgs } from 'node:util';
const commands = {
deploy: { env: { type: 'string', short: 'e' }, 'dry-run': { type: 'boolean' } },
rollback: { to: { type: 'string' } },
};
function parseCli(argv) {
const [command, ...rest] = argv;
if (!Object.hasOwn(commands, command)) {
return { error: `unknown command "${command}", expected ${Object.keys(commands).join(' or ')}` };
}
const { values, positionals } = parseArgs({ args: rest, options: commands[command], allowPositionals: true });
return { command, options: { ...values }, positionals };
}
console.log(parseCli(['deploy', '-e', 'prod', '--dry-run', 'api']));
console.log(parseCli(['rollback', '--to', 'v41']));
console.log(parseCli(['destroy']));{
command: 'deploy',
options: { env: 'prod', 'dry-run': true },
positionals: [ 'api' ]
}
{ command: 'rollback', options: { to: 'v41' }, positionals: [] }
{ error: 'unknown command "destroy", expected deploy or rollback' }Each command gets its own options table, so --to is valid for rollback and rejected for deploy by parseArgs's strict mode. Object.hasOwn guards the lookup, so typing constructor as a command does not find a method on the prototype. Spreading values turns the null-prototype result into a plain object. In real use pass process.argv.slice(2). See util.parseArgs.
Options placed before the command, such as cli --verbose deploy, are read as the command name here. Support global flags by parsing with tokens: true and strict: false first, or by documenting that they go after the command.