Tuesday, May 1, 2018

How to use Commandline Arguments in Node.js?

Commandline arguments are quite handy for small programs mostly required for interviews or testing your function. It could be another way to test your method in TDD (Test Driven Development) approach. Below is the sample program that you can write to understand how to pass a command-line argument to a node.js application and how to handle it.

// Lodash library
const _ = require('lodash');

// Function that goes through each CommandLine Arguments and prints it to the console.
const runApp = () => {
  console.log(`\nTotal Arguments: ${process.argv.length}`);
  console.log('\nPrint all the arguments:');
  console.log('*********************');
  _.map(process.argv, (arg) => {
    console.log(`[${process.argv.indexOf(arg)}]: ${arg}`);
  });
};

// Calling the function.
runApp();

Above code is a simple example of using getting command-line arguments into the program and use it as an input to the function. Below you can learn how to run the program:

$ node index.js abc xyz
Total Arguments: 2
Print all the arguments:
*********************
[0]: /Users/user1/.nvm/versions/node/v9.11.1/bin/node
[1]: /Users/user1/test/nodejs/cmdarguments/index.js

In above example, you can see that process.argv is an array type property and by default contains 2 arguments. One is the direct path of node.js version installed and used to run this program and another is the file path we are running as a node.js program. Now, if we add our own argument values then it will be listed from the index number 3 and so on. For more details look the example below:
$ node index.js abc xyz 123 34.56
Total Arguments: 6
Print all the arguments:
*********************
[0]: /Users/user1/.nvm/versions/node/v9.11.1/bin/node
[1]: /Users/user1/test/nodejs/cmdarguments/index.js
[2]: abc
[3]: xyz
[4]: 123
[5]: 34.56
One thing you can observe here that process.argv can handle any type of data which includes string, integer, float, decimal etc. So, we have to be careful before we process these values.