Working with Command-Line Arguments

1. Accessing process.argv Array

SnippetResult
process.argv.slice(2)Just user args
process.execArgvArgs to node itself (e.g. --inspect)

2. Parsing Arguments Manually

Example: Tiny parser

const args = process.argv.slice(2);
const opts = {};
for (let i = 0; i < args.length; i++) {
  if (args[i].startsWith("--")) opts[args[i].slice(2)] = args[i+1];
}

3. Using util.parseArgs for CLI

Example: util.parseArgs v18.3+

import { parseArgs } from "node:util";
const { values, positionals } = parseArgs({
  options: {
    port: { type: "string", short: "p", default: "3000" },
    verbose: { type: "boolean", short: "v" }
  },
  allowPositionals: true
});
Option TypeNotes
stringCaptures next token
booleanFlag presence
multiple: trueCollect array

4. Using commander for CLI

Example

import { Command } from "commander";
const program = new Command();
program
  .name("mycli")
  .option("-p, --port <number>", "port", "3000")
  .command("serve").action(() => startServer())
  .parse();

5. Using yargs for Argument Parsing

FeatureNotes
Subcommands.command("build", ...)
Auto help/version.help().version()
Type coercion.number("port")
Validation.demandOption(["file"])

6. Handling Flags and Options (--flag, -f)

FormConvention
--name valueLong option
--name=valueLong with equals
-n value / -nvShort / combined
--no-colorNegated boolean

7. Using Positional Arguments

ToolAccess
util.parseArgspositionals
commander.argument("<file>")
yargsargv._

8. Implementing Subcommands

Example: commander subcommands

program
  .command("user <action>")
  .description("manage users")
  .action((action) => { /* ... */ });

9. Adding Help and Usage Info

LibraryAuto Help Flag
commander-h, --help
yargs--help
util.parseArgsBuild manually

10. Validating User Input

StrategyExample
Schema validationZod / Joi
Library hookscommander .choices([...])
Custom predicatesThrow with friendly message

11. Creating Interactive CLIs

LibraryUse
Inquirer / PromptsInteractive prompts
EnquirerLightweight prompts
Chalk / PicocolorsColorized output
OraSpinners
InkReact-like CLI rendering