How to parse command line arguments in Node.js?

Command-line arguments are the additional information that you pass to the program. It is mentioned after the name of the program. Arguments are separated by space; if an argument has space, then wrap that argument in single quotes or double-quotes.

In Node.js, you read command line arguments using the global object called process. The process object has a property argv using which you access all the command line arguments passed to the program. The full form of argv is argument vector. It is an array that contains all the arguments passed to the program. The zeroth element of the argv is the path to the Node.js executable on your computer, and the first element is the path to the file you want to execute. Command-line arguments start from the second index position.

The following example prints command-line arguments passed to the program:

index.js
console.log("Command line arguments:");
console.log(process.argv);

Here is how you pass command line arguments in Node.js.

$node index.js 123 "Mohit Natani" true

Output

Command line arguments:
[
  '/usr/local/bin/node',
  '/home/projects/node-wqvkd5/src/app.js',
  '123',
  'Mohit Natani',
  'true'
]

Explanation of the code:

  • index.js is the file that you want to execute. Three command line arguments are passed to the program, 123, "Mohit Natani", and true.
  • All the command line arguments, filename, and node command are printed on the console.

Use the array slice() method to get away with the zeroth and first element of the argv.

console.log(process.argv.slice(2));

Output

[ '123', 'Mohit Natani', 'true' ]

Let's see an example in which we will add two numbers that are passed as command-line arguments.

let a = parseFloat(process.argv[2]);
let b = parseFloat(process.argv[3]);

let sum = a + b;
console.log(`Sum of ${a} and ${b} is ${sum}`);

You execute the above program by passing 10 and 20 as command-line arguments

$node index.js 10 20

Output

Sum of 10 and 20 is 30

The first command-line argument is stored in a variable a and the second one in a variable b. The addition is computed, and the result is displayed on the console.

Recommended Posts