87

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.

Justin R.
  • 895
  • 1
  • 6
  • 4
  • 26
    FWIW, calling it `argv` is a [convention inherited from C](http://stackoverflow.com/q/3024197/201952), where it means *argument vector* (array). – josh3736 Mar 06 '14 at 03:20

9 Answers9

89

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.

salezica
  • 74,081
  • 25
  • 105
  • 166
32

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

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
6

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.

maerics
  • 151,642
  • 46
  • 269
  • 291
3

In the node.js, the command line arguments are always stored in an array. In that array, the first element is the node command we refer to because we begin the command line with word “node”. The second element is the javascript (JS) file we refer to that often comes after the node command.

As we know, in the first element in JS array begins from zero, the second element is 1, and it goes 2, 3, 4 and on. Let’s name this array process.argv and add command line arguments x and y. Then, this is how we are going to call these elements:

var process.argv = ['node', 'file.js', ‘x’, ‘y’];
var process.argv [0] = node;
var process.argv [1]= file.js;
var process.argv[2] = x;
var process.argv[3] = y;

In short, element 0 and 1 are native to node.js, and we don't use them when we write any command line argument. That's why we ignore 0 and 1 and always begin from 2.

If we want to loop through the command line arguments, again we have to start from 2. Here is what we use for looping.

for (i = 2; i < process.argv.length; i++){
console.log(process.argv[i]);
}
Kadiro Elemo
  • 81
  • 1
  • 3
3

My answer is not about on how process.argv works -'cause there is a lot of answers here-, instead, it is on how you can get the values using array destructuring syntax.

For example, if you run your script with:

node app.js arthur 35

you can get those values in a more readable way like this:

const [node, script, name, age] = process.argv;

console.log(node); // node
console.log(script); // app.js
console.log(name); // arthur
console.log(age); // 35

You can omit the first and second places of your process.argv, and stay only with name and age:

const [, , name, age] = process.argv;

If you want all the arguments in an array, you can do it using the rest syntax, that collects multiple elements and condenses them into a single element like this:

const [node, script, ...params] = process.argv;

console.log(node); // node
console.log(script); // app.js
console.log(params); // [ 'arthur', '35' ]

and of course, you can omit the first and second places of your process.argv, and stay only with your params:

const [, , ...params] = process.argv;
robe007
  • 3,523
  • 4
  • 33
  • 59
1

When you execute it like:

node code.js <argument> <argument>....

It take into account all command line invocation. For process.argv[] array will have ["node","code.js","<argument>",...]
Because of that your arguments that in array start with index 2

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66
0

app.js

const getHasCli = (prefix, alias = undefined) => {
  const prefixIndex = process.argv.findIndex(
    (arg) => arg === prefix || (alias && arg === alias)
  );
  return prefixIndex > 0;
};

const getCliData = (prefix, alias = undefined) => {
  let data = undefined;
  const prefixIndex = process.argv.findIndex(
    (arg) => arg === prefix || (alias && arg === alias)
  );
  if (prefixIndex > 0) {
    const cliData = process.argv[prefixIndex + 1] ?? undefined;
    if (cliData) {
      data = cliData.includes("-") ? undefined : cliData;
    }
  }
  return data;
};

(async () => {
  console.log(getCliData("--dir"));
  console.log(getCliData("--outDir"));
  console.log(getHasCli("--delete"));
  console.log(getHasCli("--ignore"));
})();

Example usage

node app.js --dir "./public" --delete

Return

./public
undefined
true
false
General Grievance
  • 4,555
  • 31
  • 31
  • 45
0

I realize that your question has been answered and, that your explanation describes some criteria this answer does not meet. However, your question's title seems to imply something other than the description.

I.e. What does "argv" mean? vs. What's in "argv"?. I wanted to know the answer to the first question rather than the last and I hit this question due to the title's phrasing.

The answer, to: What does "argv" mean?, I found out, is due to NodeJS's V8-heritage. The Javascript-engine V8 is written in C++ and in C++ the main() function (application entry-point) is most often written as:

int main(int argc, char* argv[])

Where:

argc is the amount of arguments supplied i.e. the argument-count and,

argv is a pointer to a "vector" i.e. the argument-vector.

NodeJS provides process.argv as an array so the argc used in the C++ main function can be replaced by process.argv.length and does not need to be provided.

To the best of my knowledge that's what argv "means" and where it "came from". Hope this helps other curious souls out there.

Byebye
  • 934
  • 7
  • 24
-3

process.agrv[i]- basically loops through the command line arguments passed in the terminal while executing the file. for example- If you run the file as
$ node prog.js 1 2 3 , then process.argv[0]=1 and so on..

sugandh goyal
  • 325
  • 2
  • 4
  • 14