Nodejs command line arguments parser example

 Posted On  | Yashwant Chavan 

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.

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 ]


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0221 seconds.