process.argv

Read command-line arguments passed to your program.

Syntaxconst args = process.argv.slice(2);

process.argv is an array of the command-line arguments used to start the program.

What is inside it

  • argv[0] — the path to the node executable.
  • argv[1] — the path to your script.
  • argv[2] and beyond — the arguments you passed.

So the useful values start at index 2. Slice them off to work with just your arguments.

Example

Example · javascript
// greet.js — run: node greet.js Ada 36
const args = process.argv.slice(2);
const name = args[0];
const age = Number(args[1]);
console.log(`Hello ${name}, next year you turn ${age + 1}.`);

When to use it

  • A database seeder script reads `node seed.js --env staging` from `process.argv` to choose which database to populate.
  • A build tool parses `process.argv` to accept `--minify` and `--sourcemap` flags without pulling in a full CLI library.
  • An internal script uses the third element of `process.argv` as the target directory path when invoked via `node copy.js ./src`.

More examples

Inspect raw argv

Logs the full `process.argv` array -- the first two entries are always the node binary and the script path.

Example · js
// node show-args.js hello world
console.log(process.argv);
// [
//   '/usr/local/bin/node',  // argv[0]
//   '/path/to/show-args.js', // argv[1]
//   'hello',                 // argv[2]
//   'world'                  // argv[3]
// ]

Parse positional arguments

Destructures `process.argv` skipping the first two fixed entries to extract user-supplied arguments.

Example · js
// node greet.js Alice 30
const [,, name = 'World', age = '0'] = process.argv;
console.log(`Hello, ${name}! You are ${age} years old.`);

Parse named flags manually

Parses `--key=value` and boolean flags from `process.argv` without an external library.

Example · js
// node deploy.js --env=production --dry-run
const args = process.argv.slice(2);
const flags = Object.fromEntries(
  args.map(a => a.replace('--', '').split('='))
);
console.log(flags.env);     // 'production'
console.log('dry-run' in flags); // true

Discussion

  • Be the first to comment on this lesson.