Node Js - Read user inputs from the command Line

Node js developer can read/parse the command Line arguments using Process.argv.
Process.argv property returns an array of arguments. It tells you what are arguments being passed to your code.


A process in Node js is a global object which has information about the current node js process. The process object is just like a document object on the browser when we work with Javascript at the client side which has information about the DOM.

Since Process is a global object in Node, you do not have to import it into your file, It is available to you without any require() but you have the option to explicitly access it using require().



const process = require('process')

Read the arguments using: process.argv



Now, In the terminal 



We have passed three arguments to the Node using the command line and read them using process.argv and it returns a string array of the arguments we have passed in the command line.



Note: The first two elements in the array are returned by Node Js, we have not passed them.

The first element is the absolute pathname of the executable that started the Node js Process.



The Second Element is the Path of the Javascript file that is being executed i.e helloworld.js


You can read a particular element from the array using its index.
Note: process.argv0 or process.argv[0] returns the first element.
Iterate through the arguments using foreach

products.js

process.argv.forEach((val,index) =>{
console.log(`${index}: ${val}`)
})



Output:




Read Key-Value pairs from Commandline 

Node doesn't extract the key-value pairs from the command line arguments, It returns them an array element. You have to extract them on your own.


If you have to read the name key from the arguments:

console.log(process.argv.slice(3))

Output:

I hope you liked this post 😊. Please share and help your friends.