Nodejs command line arguments parser example

By Yashwant Chavan, Views 4143, Date 15-Feb-2017

Most the time we need to provide inputs (parameters) to node application, So in this tutorial, You will learn how to pass command line arguments to the Node.js application.

tags nodejs

Using process.argv

process.argv is any array which contains the command line arguments.

If you observe output, first element is C:\Program Files\nodejs\node.exe

second element will be the name of the JavaScript file (C:\javaworkspace\NodejsExamples\node-example.js)

remaining elements will be command line arguments which you have passed (foo and bar).

console.log("command line arguments:- " + process.argv);
console.log("total number of arguments:- " + process.argv.length);

process.argv.forEach(function(val, index, array) {
    console.log(index + ' - [ ' + val + ' ] ');

Run & Execute

C:\javaworkspace\NodejsExamples>node node-example.js foo bar
command line arguments:- C:\Program Files\nodejs\node.exe,C:\javaworkspace\NodejsExamples\node-example.js,foo,bar

total number of arguments:- 4

0 - [ C:\Program Files\nodejs\node.exe ]
1 - [ C:\javaworkspace\NodejsExamples\node-example.js ]
2 - [ foo ]
3 - [ bar ]

Yashwant Chavan

Yashwant Chavan

Hi there! I am founder of and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: