Node.js | Yargs Module

Yargs module is used for creating your own command-line commands in node.js and helps in generating an elegant user interface. This module makes command-line arguments flexible and easy to use.

Installation of yargs module:

  1. You can visit the link Install yargs module. You can install this package by using this command.
    npm install yargs
  2. After installing yargs you can check your yargs version in command prompt using the command.
    npm version yargs
  3. After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.
    node index.js

Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

const yargs = require('yargs')
   
// Customize yargs version
yargs.version('1.1.0')
   
// Create add command
yargs.command({
    command: 'add',
    describe: 'Adds two number',
    builder: {
        firstNumber: {
            describe: 'First Number',
            demandOption: true// Required
            type: 'number'     
        },
        secondNumber: {  
            describe: 'Second Number',
            demandOption: true,
            type: 'number'
        }
    },
  
    // Function for your command
    handler(argv) {
        console.log("Result:"
            (argv.firstNumber+argv.secondNumber))
    }
})
   
yargs.parse() // To set above changes

chevron_right


Steps to run the program:

  1. The project structure will look like this:
    project structure
  2. Make sure you have install express and yargs module using following commands:
    npm install express
    npm install yargs
  3. Run index.js file using below command:
    node index.js

    After running this above command, now yargs command is set, you can use it as shown below:

    node index.js add --firstNumber=4 --secondNumber=10

    Output of above command

So this is how you can use yargs module for making your own command-line arguments command thereby making it more interactive.

My Personal Notes arrow_drop_up

To obtain a position of responsibility that utilizes my skills and keen to work in an environment where I can enrich my knowledge

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.