Deviopath › Node.js

Parse Command-Line Arguments

Medium · CLI

A CLI reads its options from process.argv.slice(2). Write parseArgs(argv) that turns that array into { flags, positionals }. Values stay strings ("3000" is not converted to a number).

Check each argument in this order:

- --: every argument after it is positional, even if it starts with -.

- --name=value: flags.name = "value" (split at the first =, so the value may contain =).

- --no-name: flags.name = false.

- --name: if the next argument exists and does not start with -, it is the value (and is consumed). Otherwise flags.name = true.

- -abc: short flags, each letter becomes true. Short flags never take a value.

- Anything else (including a lone -) is a positional.

If a flag is repeated, the later one wins.

Next: Parse a .env File