
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
console.log(process.argv); 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', 'C:\\Users\\index.js', 'first_arg', 'second=arg', 'third_arg' ] 0: node 1: C:\Users\\index.js 2: first_arg 3: second=arg 4: third_arg
Leave a Reply