Pass parameter to Node.js application from command prompt

Introduction

 
You can get command-line arguments passed to your node.js application by using process.argv. process.argv is actually an array. So if you want values, out of this array you'll either have to use a loop or you can get simply by putting array index in process.argv.

Suppose you have a node.js app. "myscript.js".

You have passed parameters as:
  1. $node myscript.js 4 
Then in the code as in line number 2 of below code, we can get the parameter value as process.argv[2].
  1. function GetSqrt() {  
  2.     var num = process.argv[2];  
  3.     console.log(" Number is " + num + " and its square " + num * num);  
  4. }  
  5. GetSqrt(); 
You might be thinking, why I have given index number 2 and not 0. Actually process.argv[0] will return 'node' and process.argv[1] will return your script name as in this case myscript.js.

If you have multiple arguments to pass from the command prompt, you can create a separate method for argument parsing as like
  1. function GetSqrt() {  
  2.    var args = ParseArguments();  
  3.    args.forEach(function(num) {  
  4.   
  5.        console.log(" Number is " + num + " and its square " + num * num);  
  6.    })  
  7. }  
  8. GetSqrt();  
  9.   
  10. function ParseArguments() {  
  11.    var input = [];  
  12.    var arguments = process.argv;  
  13.    arguments.slice(2).forEach(function(num) {  
  14.        input.push(num);  
  15.    });  
  16.    return input;  

Here arguments.slice(2) will remove first two arguments(node and your application name) from arguments array
Next Recommended Reading Install Node.js And NPM On Windows