When we are designing any generalized program, in some cases we need to pass data from the command line.

A simple example may be a calculator, which takes input from the command line and prints the output in the console.

Reading a command line data is a basic and simple task in Node.js. When we run the program, all the arguments received from the command line is set to “process.argv” property. Process is a global object. If you want to learn more about Process, Click Here. “process.argv” is an array object which contains command line args and info about node.js files.

Prerequisites

Node Js: It should be installed in your system.

Read command line data

Below is the code to read the command line data. We are reading the “process.argv” to read command line data. you can save this code to the js file(commandline_args.js).


console.log("Displaying the command line values ")
process.argv.forEach(function(value, index){
    console.log(`${index} : ${value}`)
})

Execute the script and Output


node commandline_args argu1 data1 argu2 data2 argu3 data3

Below is the data in the process.argv object . The value at zeroth index is node js executable file path and oneth position contains the executable file path. Successive positions contain value provided in the in the command line while executing the program.

 

commandline-args-image

0 : C:\Program Files\nodejs\node.exe
1 : C:\Users\Sahajahan\Education\read-commadline\commandline_args
2 : argu1
3 : data1
4 : argu2
5 : data2
6 : argu3
7 : data3

 

You can get the whole code from the Github repo. Below is the link:

https://github.com/sahajahanAlli/read-commandline

Please Install Node module to run:
Process:
  1. Navigate to the folder(queue-example) using command prompt/windows powershell
  2. Type command “npm install”. It will install node modules.
  3. Type command “npm start”. It will show the output.

Please feel free to comments or provide the suggestion.