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.
Code
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
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.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
- Does this require external packages?
- No — `node:util` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.