Skip to content
Related Articles

Related Articles

Improve Article

How to read command line arguments in Node.js ?

  • Difficulty Level : Expert
  • Last Updated : 19 Nov, 2020

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.




    var arguments = process.argv ;
      
    console.log(arguments) ;
  • Step 2: Run index.js file using below command:
    node index.js
  • Output:Output of above command

The process.argv 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.




    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)
  • 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
Recommended Articles
Page :