skip to content

In Node.js, what does util.parseArgs return for a script's command-line arguments, and how does it treat an option it was not told about?

level: middleimportance: nice to knowfreq 15%

answer

  1. argv minus two entries
  2. an options spec of two types
  3. values and positionals
  4. strict is the default

basics

~10 s

util.parseArgs turns the script's arguments into values and positionals according to an options spec whose types are only string or boolean. Its default strict mode throws ERR_PARSE_ARGS_UNKNOWN_OPTION for an option missing from that spec.

solid answer

~40 s

`util.parseArgs({ options })` parses `process.argv` with the Node executable and script path removed, unless you pass `args` yourself. Each key of `options` is a long option name with a `type` of `'string'` or `'boolean'`, an optional one-character `short` alias, `multiple` to collect repeats into an array, and a `default` applied only when the option is absent. It returns `values`, a null-prototype object of strings and booleans, and `positionals`. `strict` defaults to `true`, so an option not in the spec throws `ERR_PARSE_ARGS_UNKNOWN_OPTION`, a string option without a value throws `ERR_PARSE_ARGS_INVALID_OPTION_VALUE`, and a positional throws `ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL` unless `allowPositionals` is set. There is no number type, so numbers still need parsing.

code

javascript · 14 lines
javascript
// node --env-file=.env serve.cjs --port 8080 -v ./public
const { parseArgs } = require('node:util');

const { values, positionals } = parseArgs({
  options: {
    port: { type: 'string', short: 'p', default: '3000' },
    verbose: { type: 'boolean', short: 'v', default: false },
  },
  allowPositionals: true,
});

const port = Number.parseInt(values.port, 10);
console.log(port, values.verbose, positionals); // 8080 true [ './public' ]
console.log(process.execArgv);                  // [ '--env-file=.env' ]

go deeper

for a junior

Recall that util.parseArgs returns values and positionals from an options spec, and that process.argv starts with the node path and the script path.

for a middle

Explain the spec fields, the default strict mode and its three error codes, and why Node's own flags sit in process.execArgv instead of process.argv.

for a senior

Show how a production command-line tool handles bad input: catch the ERR_PARSE_ARGS errors, print usage, exit non-zero, and validate numeric strings after parsing.

for a principal

Judge whether internal tooling standardises on the built-in parser, trading the richer help output of third-party parsers for zero dependencies and documented error codes.

## Why it exists Before `util.parseArgs`, a Node script that took flags either sliced `process.argv` by hand or pulled in a third-party parser. `util.parseArgs` is the built-in alternative: it has been in `node:util` since v18.3.0 and v16.17.0, and the documentation marks it as no longer experimental from v20.0.0, so every supported release line has it. ## What it parses `process.argv` is an array whose first element is the path of the Node executable and whose second is the absolute path of the entry script; the rest are the script's own arguments. Node's own flags placed **before** the script name, such as `--env-file=.env`, are not in `process.argv` at all: they are in `process.execArgv`. By default `parseArgs` reads `process.argv` with the executable and script removed, so it sees only the arguments after the script name. Passing `args` lets you parse any array instead, which is how tests feed it fixed input. ## The options spec Each key of `options` is the **long name** of an option, and each value describes it: - `type` is required and must be `'string'` or `'boolean'`; anything else is rejected when `parseArgs` validates its configuration. - `short` is a single-character alias, so `-p` can mean `--port`. - `multiple: true` collects every occurrence into an array; otherwise the **last occurrence wins**. - `default` supplies a value only when the option does not appear; it must match `type`. Two top-level switches shape the rest: - `allowPositionals` decides whether bare arguments such as file paths are accepted. It defaults to `false` when `strict` is `true`. - `allowNegative: true` lets `--no-color` set a boolean `color` option to `false` (added in v22.4.0 and v20.16.0). ## What it returns The result has `values`, a **null-prototype** object mapping each long name to a string or boolean, and `positionals`, an array of strings. With `tokens: true` it also returns the raw tokens, in input order, for custom post-processing. ## Parsing details worth knowing - **Short groups expand**: `-xy` produces one token for `-x` and one for `-y`, so `-xxx` produces three. - **Inline values work**: `--port=8080` and `--port 8080` both set `port` to `'8080'`. - **A bare `--` ends option parsing**: everything after it is treated as a positional, which is how a script passes flag-like text through untouched. - **Repeats are last-wins** unless `multiple: true`, in which case every value is collected in order. | Approach | Unknown flags | Types | Errors | |---|---|---|---| | Slicing `process.argv` by hand | whatever your code does | strings | none unless you write them | | `util.parseArgs` in strict mode | throw | string and boolean | documented `ERR_PARSE_ARGS_*` codes | | `util.parseArgs` with `strict: false` | stored in `values` | string and boolean | only spec validation | ## Strict mode and its errors `strict` defaults to `true`, and that is what makes `parseArgs` useful for a production command-line tool: | Input problem | Error code | |---|---| | An option missing from `options` | `ERR_PARSE_ARGS_UNKNOWN_OPTION` | | A string option with no value, or a boolean option given one | `ERR_PARSE_ARGS_INVALID_OPTION_VALUE` | | A positional while `allowPositionals` is `false` | `ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL` | Strict mode also refuses an ambiguous `--port --verbose`, where the value of a string option looks like another option, and suggests `--port=-XYZ` if a dash-leading value was meant. With `strict: false`, unknown options are stored in `values` instead of throwing, which is convenient for wrappers and dangerous for anything that should reject typos. ## Using it well 1. Declare every option with its type and a sensible `default`. 2. Convert string values that stand for numbers with `Number.parseInt` and reject `NaN`, because there is no number type. 3. Catch the `ERR_PARSE_ARGS_*` errors at the top of the script, print a usage line and exit with a non-zero code. 4. Keep Node's own flags before the script name and the script's flags after it, so each lands in the right array. 5. Pass a fixed `args` array in unit tests, so the parser's behaviour is tested without touching `process.argv`. The result is a small, dependency-free command-line interface whose behaviour on bad input is predictable and documented.

  • Why does util.parseArgs never see a flag such as --env-file=.env written before the script name?
    Because Node consumes its own options before the entry point and records them in `process.execArgv`, not in `process.argv`. `process.argv` keeps the executable path, the script path and the arguments after the script, and `parseArgs` drops the first two by default, so it only ever parses the script's own arguments.
  • When would you set strict: false on util.parseArgs, and what do you give up?
    When the script is a wrapper that forwards unknown options to something else and must not reject them. With `strict: false`, unknown options are stored in `values` and positionals are allowed, so a typo such as `--prot` no longer fails loudly; the script has to validate `values` itself.

  • util.parseArgs silently ignores options that are not in the spec.
  • util.parseArgs can return numbers when an option is given a number type.
  • util.parseArgs sees Node flags passed before the script name.
  • A default value is applied even when the option is passed with an empty string.