How to read command line arguments in Node.js ?

Command-line arguments (CLI) are strings of text used to pass additional information to a program when an application is running through the command line interface of an operating system. We can easily read these arguments by the global object in node i.e. process object.

Below is the approach with the proper example.

Example 1:

  • Step 1: Save a file as index.js and paste the below code inside the file.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    var arguments = process.argv ;
      
    console.log(arguments) ;

    chevron_right

    
    

  • Step 2: Run index.js file using below command:
    node index.js
  • Output:Output of above command

The process.arg contains an array where the 0th index contains the node executable path, 1st index contains the path to your current file and then the rest index contains the passed arguments.

Example 2: Program to add two numbers passed as arguments.

  • Step 1: Save the file as index1.js and paste the below code inside the file.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    var arguments = process.argv
      
    function add(a, b) {
      
        // To extract number from string
        return parseInt(a)+parseInt(b) 
    }
      
    var sum = add(arguments[2], arguments[3])
      
    console.log("Addition of 2, 3 is ", sum)

    chevron_right

    
    

  • Step 2: Run index1.js file using below command:
    node index1.js
  • Output:Output of above command

So this is how we can handle arguments in Node.js. The args module is very popular for handling command-line arguments. It provides various features like adding our own command to work and so on.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.