CodeBlanks Logo Icon CodeBlanks

process.argv

Learn command-line arguments with process.argv.

What is process.argv?

process.argv is an array that holds command-line arguments in Node.js. The values you pass when running the program are listed here.

Example: node calc.js 5 3. Here process.argv[0] is the node path, process.argv[1] is the path of calc.js, process.argv[2] is '5' and process.argv[3] is '3'.

Note: these values come as strings. To use them as numbers, you must convert with Number(...).

Converting with Number

Values from process.argv are strings. To do numeric operations, you must convert them to numbers with Number(...).

Example: const a = Number(process.argv[2]). This converts the string '5' to the number 5. Now math operations like a + b work correctly.

If you add without converting, '5' + '3' becomes '53'; this is an unwanted result. Do not forget to convert!

Practice Read from process.argv

Read two numbers from process.argv: const a = Number(process.argv[2]) and const b = Number(process.argv[3]). All functions are defined; the file ends with console.log('Result: ' + add(a, b)). The program is run as node calc.js 5 3.

Starter code

index.js
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

function multiply(a, b) {
  return a * b;
}

function divide(a, b) {
  if (b === 0) return 0;
  return a / b;
}

// Read a and b from process.argv

console.log("Result: " + add(a, b));

Sample solution

index.js
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

function multiply(a, b) {
  return a * b;
}

function divide(a, b) {
  if (b === 0) return 0;
  return a / b;
}

const a = Number(process.argv[2]);
const b = Number(process.argv[3]);

console.log("Result: " + add(a, b));

Expected output

Result: 8

Questions and answers

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

1 What is process.argv[0]?

  • The first user argument
  • The path of the node executable Correct answer
  • It throws an error
  • An empty value

Explanation: process.argv[0] is the node path.

2 Read argv

Question
const a = Number(process.argv[____]);
Answer
const a = Number(process.argv[2]);

Explanation: The first user argument is at index 2.

3 Match the CLI concepts

Term Meaning
process.argv Command-line arguments
process.argv[0] node path
process.argv[2] First user argument
Number(...) Convert string to number

All lessons in Beginner