How to use yargs module In NodeJS

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


How to parse command line arguments in Node ?

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

Table of Content

  • Using process.argv
  • Using yargs module

Similar Reads

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....

Method 2: Using yargs module:

...