How to parse command line arguments in node.js ?
Command-line arguments are strings of text used to pass additional information to a program when an application is run through the command-line interface (CLI) of an operating system. In Node.js, all command-line arguments received by the shell are given to the process in an array called argv(arguments-values).
We will use two methods to parse command-line arguments via process.argv array as well as popular package yargs
Note: The first two elements of process.argv array are always present even if we don’t pass any arguments.
Example 1: Filename: gfg.js
Run the gfg.js file using the following command by passing arguments:
node gfg.js I Love GeeksforGeeks
Example 2: Program to perform an arithmetic operation according to the arguments passed via cmd.
Run the arthimatic.js file by passing the following arguments:
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: Filename: yarg.js
To run the file, execute the following command:
- 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