// Lodash libraryconst _ = 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 xyzTotal Arguments: 2Print 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:
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.$ node index.js abc xyz 123 34.56Total Arguments: 6Print 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