Skip to content
jshacks.dev
Node.js

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.

2 min read
Summarize in AI

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.

cli.mjsJavaScript
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']));
Text
{
  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.

Taggednode 24
Share

More snippets

Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.