How to pass command line arguments to Node.js

Generally developers who are coming from client side JavaScript development world don’t have to deal with the command line arguments.
But when developing Node.js application often developers need the Linux/Unix command line arguments.

Node.js provides an easy way to access command line argument in your code.
The arguments given from command line are stored in process.argv.
process.argv is an array containing the list of command line arguments.

  • The first element of process.argv is ‘node’.
  • The second element is the JavaScript file name.
  • Next element is any command line argument you will give.

Lets say we have a file called app.js. write the following code in app.js


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

now run you app.js code using following command and see the output.

$ node app.js first_arg second=arg third_arg
[ 'node',
'third_arg' ]
0: node
1: C:\Users\\index.js
2: first_arg
3: second=arg
4: third_arg


Node.js Certification Training at!

Partner Sites

Be the first to comment

Leave a Reply

Your email address will not be published.