Node.js

Parse command-line options with util.parseArgs

Use util.parseArgs for a small command-line interface with named options. Declare option types and decide explicitly whether unexpected flags or positional arguments are accepted.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import {parseArgs} from "node:util";
const {values, positionals} = parseArgs({
  args: ["--format", "json", "--verbose", "input.txt"],
  options: {format: {type: "string"}, verbose: {type: "boolean"}},
  allowPositionals: true, strict: true
});
console.log(values.format, values.verbose, positionals[0]);

How it works

The args array is explicit so the example behaves the same regardless of how it is launched. A real CLI can use process.argv.slice(2). Strict parsing catches unknown flags instead of silently accepting misspelled options.

Limits and mistakes

A parsed string still needs domain validation. For example, format should be restricted to the values your program actually supports. Parsing does not open files, sanitize paths, or generate a useful help message automatically.

Check the result

Expect json true input.txt. Add an unknown flag and confirm strict mode rejects it. Check missing values and repeated options against the intended CLI contract.

Sources

Reference documentation for the behavior used in this guide: