CodeBlanks Logo Icon CodeBlanks

process.argv

Learn CLI arguments with process.argv.

What is process.argv?

process.argv is an array that holds the command-line arguments. When Node.js runs a script it fills this array automatically. The first two elements are fixed; the rest are the arguments the user passed.

Specifically: argv[0] holds the path to the Node.js executable and argv[1] holds the path to the script being run. argv[2] and beyond are the arguments the user typed on the command line. For example, with node app.js hello the value of argv[2] is hello. This lets you pass data into your program from outside.

Reading values from argv

You read the first user argument with process.argv[2]. But if the user gives no argument, this value is undefined. You can replace it with a default using the || operator.

For example, writing const name = process.argv[2] || "Node"; uses the argument if the user gave one, otherwise "Node". This pattern is very common in CLI tools: the program does not crash on missing arguments, it runs with a sensible default. For more complex cases you can loop over the process.argv array and extract options shaped like --flag.

Practice Read the first argument and print it

Read the first user argument with process.argv[2]. If it is missing, use "Node" as a default with ||. Print it with console.log.

Starter code

index.js
// Read the first user argument
// If missing, use "Node"
// Print with console.log
// write here

Sample solution

index.js
const name = process.argv[2] || "Node";
console.log(name);

Expected output

Node

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 At which index is the first user argument in process.argv?

index.js
process.argv
  • argv[1]
  • argv[0]
  • argv[2] Correct answer
  • argv[3]

Explanation: argv[0] and argv[1] are Node and the script path; the first user argument is argv[2].

2 Read the first argument

Question
const name = process.argv[____] || "Node";
Answer
const name = process.argv[2] || "Node";

Explanation: argv[2] is the first user argument.

3 Match each index to its role

Term Meaning
argv[0] Node path
argv[1] Script path
argv[2] First user argument
argv[3] Second user argument

All lessons in Intermediate