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.
Code
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: trueHow 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
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.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.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
- Do I need to install anything before running this?
- Nothing needs installing: `node:util` ships with Node.js itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.