CLI Arguments

`process.argv` and `parseArgs` — Reading the Command Line

CLI Arguments

Read flags and positional arguments. Use the built-in parseArgs for serious CLI parsing.

3 min read Level 1/5 #nodejs#cli#args
What you'll learn
  • Read process.argv
  • Use util.parseArgs for flags
  • Build a tiny CLI

Every Node script gets called with arguments. They live on process.argv.

process.argv

// args.mjs
console.log(process.argv);
$ node args.mjs hello world
[
  '/usr/local/bin/node',
  '/path/to/args.mjs',
  'hello',
  'world'
]
  • [0] — Node binary path
  • [1] — your script path
  • [2]+ — actual user arguments

Slice off the boring parts:

const args = process.argv.slice(2);
console.log(args);   // ['hello', 'world']

util.parseArgs (Built-in)

For flags, defaults, and types — use the built-in parser:

import { parseArgs } from "node:util";

const { values, positionals } = parseArgs({
  options: {
    name:    { type: "string",  short: "n", default: "world" },
    verbose: { type: "boolean", short: "v", default: false },
  },
  allowPositionals: true,
});

console.log(values);       // { name: 'ada', verbose: true }
console.log(positionals);  // ['extra']
$ node greet.mjs --name ada -v extra
{ name: 'ada', verbose: true }
[ 'extra' ]

A Tiny CLI

#!/usr/bin/env node
import { parseArgs } from "node:util";

const { values } = parseArgs({
  options: {
    name: { type: "string", short: "n", default: "stranger" },
  },
});

console.log(`Hello, ${values.name}!`);

Save as greet.mjs, run node greet.mjs --name AdaHello, Ada!.

For Bigger CLIs

parseArgs is good for ~80% of cases. For subcommands, help text, auto-completion: reach for commander, yargs, or cac. But don’t add a dep until parseArgs actually falls short.

Environment Variables →