How do I pass command line arguments to a Node.js program?

Computers & Internet

How do I pass command line arguments to a Node.js program?

What are command line arguments?


Parameters or arguments passed to a script from terminal or command prompt (Windows) is known as command line arguments.


All major programming languages provides some kind of facility to achive this.
In C, C++, Java all provides a way to accept command line arguments in the form of some kind of an array. The array is called argv. The argv stands for argument values. 


Let's do it in Node.js


Create an app.js with following statements:


// All arguments array
console.log("All arguments:\n", process.argv)

// Get invidiual arguments one by one
console.log("\nIndividual Aguments:")
console.log("1: ", process.argv[0])
console.log("2: ", process.argv[1])
console.log("3: ", process.argv[2])
console.log("3: ", process.argv[3])
console.log("7: ", process.argv[7])

Now, try passing some arguments. For this example I have considered long string to get numerous amount of parameters.


$ node app.js factober is knowledge and fact website.

Output:


How do I pass command line arguments to a Node.js program?