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. console.log(" Number is " + num + " and its square " + num * num);
  5. })
  6. }
  7. GetSqrt();
  8. function ParseArguments() {
  9. var input = [];
  10. var arguments = process.argv;
  11. arguments.slice(2).forEach(function(num) {
  12. input.push(num);
  13. });
  14. return input;
  15. }
Here arguments.slice(2) will remove first two arguments(node and your application name) from arguments array