When a program starts the parameters or arguments send to the program using command prompt called Command-line argument or command-line parameter. A program can have many command-line arguments. We can alter the operation of program with command-line argument.
NodeJS provides an easy way to read the data from command-line. By default, it provides a global object “process” that has an element “argv” (short for ‘argument values’). Since process is a global object, it can be accessed from anywhere. We can use process object to avail environment information, read environment variables, communicate with the terminal and so on. “argv “, is an array holding the information provided on the command-line.
Let us look at an example for the same. I have divided the entire process into two easy steps.
Step 1: - Create a file name app.js and write down the following code.
Step 2: - Run the file by typing following command “node app.js John Steven ”
var firstName = process.argv;
var lastName = process.argv;
console.log("Name:", firstName +" "+lastName);
Output : - Name: john steven
- The first parameter is always node itself in the array.
- The second parameter is the file.
- The rest of the parameters are the values supplied using command-line.
I hope you like the blog. What else can be included? Feel free to drop a message, feedback or query in the comments section below.