Open In App

How to parse command line arguments in Node ?

Last Updated : 18 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Command-line arguments, in the context of a command-line interface (CLI), are text strings that provide extra information to a program when it is executed. In Nodejs, these arguments are accessible through an array known as `argv` (arguments values), where the shell passes all received command-line arguments to the running process.

We will use two methods to parse command-line arguments via process.argv array as well as popular package yargs

Method 1: Using process.argv:

The most straightforward method to access command-line arguments in Node.js is through the `process.argv` array. This array is exposed by Node.js for each running process. The first element of `process.argv` is the file system path to the Node executable file, the second element is the path to the currently executing JavaScript file, and the subsequent elements constitute the arguments provided via the command line.

Note: The first two elements of process.argv array are always present even if we don’t pass any arguments.

Example 1: Below is the example to show the usage of process.argv:

Javascript




for (let i = 0; i < process.argv.length; ++i) {
    console.log(
        `index ${i}
        argument ->
        ${process.argv[i]}
        `
    );
}


Run the gfg.js file using the following command by passing arguments:

node gfg.js I Love GeeksforGeeks

Output:

Using process.argv

Example 2: Program to perform an arithmetic operation according to the arguments passed via cmd.

Javascript




// To trim first 2 elements
const arg = process.argv.slice(2);
 
arg[1] = Number(arg[1]);
arg[2] = Number(arg[2]);
 
switch (arg[0]) {
    case '+':
        console.log(`Result of ${arg[1]}
        + ${arg[2]} = ${arg[1] + arg[2]}`);
        break;
 
    case '*':
        console.log(`Result of ${arg[1]}
        * ${arg[2]} = ${arg[1] * arg[2]}`);
        break;
 
    case '-':
        console.log(`Result of ${arg[1]}
        - ${arg[2]} = ${arg[1] - arg[2]}`);
        break;
 
    case '/':
        if (arg[2] == 0) {
            console.log(
                'cannot be divided by zero!!');
        } else {
            console.log(`Result of ${arg[1]}
            / ${arg[2]} = ${arg[1] / arg[2]}`);
        }
        break;
 
    case '%':
        if (arg[2] == 0) {
            console.log(
                'cannot be divided by zero!!');
        } else {
            console.log(`Result of ${arg[1]}
            % ${arg[2]} = ${arg[1] % arg[2]}`);
        }
        break;
 
    default: console.log(
        `operation cannot be performed!!`);
}


Steps to run the arithmetic.js file by passing the following arguments:

Output:

Program to perform the arithmetic operation according to the arguments passed via cmd.

Method 2: Using yargs module:

Passing arguments via cmd becomes tedious when we start working with flags or if your server needed a lot of arguments.

app -h host -p port -r -v -b --quiet -x -o outfile

To solve this, we can use the third library module such as yargs to parse the arguments passed via cmd. In this module, you can pass arguments as a key-value pair and later access them with the help of a key. The .argv gets the arguments as a plain old object.

Install yargs module using the following command:

npm install yargs --save

Example: Below is the example to show the usage of yargs module:

Javascript




const args = require('yargs').argv;
console.log(args);
console.log(`Language : ${args.language}`);
console.log(`IDE : ${args.ide}`);


To run the file, execute the following command: 

node yarg.js --language=javascript --ide=GFG_IDE command1 command2 --b --v

Output:

Using yargs module

Note:

  • argv.$0 contains the name of the script file which is to execute.
  • argv._ is an array containing each element not attached to an option(or flag) these elements are referred to as commands in yargs.
  • The flags such as argv.time, argv.b, etc become the property of the argv. The flags must be passed as –flag. Example: node app.js –b


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads