Search code examples
node.js

Could someone explain what "process.argv" means in node.js please?


I'm currently learning node.js, and I was just curious what that meant, I am learning and could you tell me why this code does what it does:

var result = 0;

  for (var i = 2; i < process.argv.length; i++){
    result += Number(process.argv[i]);
}
  console.log(result);

I know it adds the numbers that you add to the command line, but why does "i" start with 2? I understand the for loop, so you don't have to go into detail about that.

Thank you so much in advance.


Solution

  • Do a quick console.log(process.argv) and you'll immediately spot the problem.

    It starts on 2 because process.argv contains the whole command-line invocation:

    process.argv = ['node', 'yourscript.js', ...]
    

    Elements 0 and 1 are not "arguments" from the script's point of view, but they are for the shell that invoked the script.

    Meanwhile if process.argv[2] is --, it also needs to be skipped.