Node.js Environment process.argv command line arguments

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

process.argv is 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.

Code Example:

Output sum of all command line arguments

index.js

var sum = 0;
for (i = 2; i < process.argv.length; i++) {
    sum += Number(process.argv[i]);
}

console.log(sum);

Usage Exaple:

node index.js 2 5 6 7

Output will be 20

A brief explanation of the code:

Here in for loop for (i = 2; i < process.argv.length; i++) loop begins with 2 because first two elements in process.argv array always is ['path/to/node.exe', 'path/to/js/file', ...]

Converting to number Number(process.argv[i]) because elements in process.argv array always is string



Got any Node.js Question?