util.parseArgs Parses CLI Flags

util.parseArgs validates declared flags: booleans default to false, string options can repeat into arrays, and positionals come back separately.

JavascriptCli Tooling

Code

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

// args 选项让 parseArgs 可以吃任意数组:单测与演示不用动 process.argv
const { values, positionals } = parseArgs({
  args: ['--verbose', '-o', 'dist', '--tag', 'beta', '--tag', 'rc', 'build', 'docs'],
  options: {
    verbose: { type: 'boolean', short: 'v' },
    out: { type: 'string', short: 'o' },
    tag: { type: 'string', multiple: true },
  },
  allowPositionals: true,
});

console.log('verbose:', values.verbose);
console.log('out:', values.out);
console.log('tag:', values.tag);
console.log('positionals:', positionals);

Output

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

verbose: true
out: dist
tag: [ 'beta', 'rc' ]
positionals: [ 'build', 'docs' ]

How it works

parseArgs comes from node:util — Node.js core modules the runtime ships with.

What to watch for

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

Applying it

Running the file prints labeled results such as verbose:, out:, tag: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

Does this require external packages?
No — `node:util` is a Node.js built-in module; nothing to install.