Nodejs read data from command line


Nodejs read data from command line

By bangarsanju12


Once we start writing nodejs based programming , we need to read data from console .Hence in this tutorial we will understand how can we read data from command line in nodejs .

We have a nodejs file named as server.js , now if we want to pass data so that we can read those data in our code , we do something like this below .

node server.js John

node server.js name=john 

Now that we have passed the data from command line arguments , lets see how we can read the data .

How to Read Data from console in Nodejs

We can read data from command line using process object in node js .Process is a global object and alaways available in any scope in your code .

  • Process object has argv property which can be used to read command line arguments once we start any nodejs processes.
  • As you can see in the above code first element passed from command line is node
  • Second element is basically the server.js which is a file and starting point of our code execution .
  • All the arguments that we want our code to consume are from third position onwards .

We can now use process to iterate through all the command line values as below .

process.argv.forEach((value, position) => {
    console.log(`${position}: ${value}`);

OutPut :-

nodejs read from command line

process.argv is an array object and we can use all the array operations to read the command line data as below .

const args = process.argv.slice(2)

Output :-

$ node server.js john
[ 'john' ]

we have processed the 3rd item by slicing array . But this wont work if we pass like below

$ node server.js NAME=john
[ 'NAME=john' ]

How to Read Arguments from Command Line Using Index name and variables

In above exampple where we have variabled passed as command line data we just need the value of the variable but using process.argv.slice(2) we are getting the variable and value both .

We can use a minimist library to read the variables as below

var parseArgs = require('minimist');
const data=(parseArgs)(process.argv.slice(2));

Now if we try something like

$node server.js name=john 


read variable nodejs command line

Did you notice the change , it still doesnt solve my problem but provides the entire 3rd argument inside an object . So in order to get the desired output as John we need to pass double dast before name of the varibale .

nodejs read arguments from console

Hence the final code to read from console using minimist library would look like below .

var parseArgs = require('minimist');
const data=(parseArgs)(process.argv.slice(2));

Please let me know in comments if you face any technical difficulty in implementing .

Happy Coding …

Leave a Comment