Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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.

like image 493
Justin R. Avatar asked Mar 06 '14 03:03

Justin R.


People also ask

What is process argv in node JS?

The process. argv() method is used for returning all the command-line arguments that were passed when the Node. js process was being launched. The first element will always contains the same value as process.

What does process argv 1 contain?

argv : An array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

What does process mean in node JS?

Node. js provides the facility to get process information such as process id, architecture, platform, version, release, uptime, upu usage etc. It can also be used to kill process, set uid, set groups, unmask etc. The process is a global object, an instance of EventEmitter, can be accessed from anywhere.


3 Answers

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.

like image 108
slezica Avatar answered Oct 08 '22 00:10

slezica


It starts with 2 because the code will be run with

node myprogram.js firstarg secondarg

So

process.argv[0] == "node"

process.argv[1] == "myprogram.js"

process.argv[2] == "firstarg"

Online docs

like image 20
Ray Toal Avatar answered Oct 07 '22 23:10

Ray Toal


Your program prints the sum of the numerical values of the "command line arguments" provided to the node script.

For example:

$ /usr/local/bin/node ./sum-process-argv.js 1 2 3
6

From the Node.js API documentation for process.argv:

An array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

In the above examples those values are:

process.argv[0] == '/usr/local/bin/node'
process.argv[1] == '/Users/maerics/src/js/sum-process-argv.js'
process.argv[2] == '1'
process.argv[3] == '2'
process.argv[4] == '3'

See also the Number(...) function/contructor for JavaScript.

like image 5
maerics Avatar answered Oct 07 '22 23:10

maerics