parseArgs tokens Route Subcommands

Parse CLI input with util.parseArgs using tokens: true to locate the subcommand positional and route the rest of the argument stream per verb.

JavascriptCli Tooling

Code

javascriptsnippet
27 lines
import { parseArgs } from 'node:util';

// tokens: true exposes the raw option/positional stream, so a CLI can find
// the subcommand itself and route the remaining arguments per verb.
const argv = ['deploy', '--env', 'staging', '--dry-run', 'api', 'web'];

const { values, tokens } = parseArgs({
  args: argv,
  allowPositionals: true,
  tokens: true,
  options: {
    env: { type: 'string' },
    'dry-run': { type: 'boolean' },
  },
});

const verbToken = tokens.find((token) => token.kind === 'positional');
const verb = verbToken?.value ?? 'help';
console.log('verb:', verb);

// everything after the first positional belongs to the subcommand
const targets = tokens
  .slice(tokens.indexOf(verbToken) + 1)
  .filter((token) => token.kind === 'positional')
  .map((token) => token.value);
console.log('targets:', targets.join(','));
console.log('env:', values.env, 'dry-run:', values['dry-run']);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

verb: deploy
targets: api,web
env: staging dry-run: true

How the snippet works

node:util supplies parseArgs — built-in surface, no package involved.

Top-level bindings argv, verbToken, verb, targets hold the demo state — nothing sits inside a function scope.

What to watch for

  • The dependency surface is just node:util, and that one is built into Node.js.

Applying it

Output lines are prefixed (verb:, targets:, env:), making each step’s effect easy to spot.

Statements that matter

const verb = verbToken?.value ?? 'help';
const verbToken = tokens.find((token) => token.kind === 'positional');
.map((token) => token.value);

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Nothing needs installing: `node:util` ships with Node.js itself.