When invoking a Node.js application on the terminal you can pass any number of arguments and arguments can be standalone or have a key and a value.
For example, let consider the below command
node app.js jose
What happens in a nutshell node.js expose an argv property, which is an array that contains all the command line invocation arguments.
The first element is the full path of the node command, the second element is the full path of the file being executed and all the additional arguments are present from the third position going forward, to check this out see the snippet below.
process.argv.forEach((val, index) => {
console.log(`${index}:${val}`);
});
You can get only the additional arguments by creating a new array that excludes the first 2 params:
const args = process.argv.slice(2);
This said consider the below snippet
const args = process.argv.slice(2);
console.log(args);
We can execute this program now
node app.js jose
Here is the result
jose
Now that we know how to accept arguments from the command line, let us built a simple calculator on top of this knowledge
const args = process.argv.slice(2);
let result = 0;
if(args.length === 0){
console.log('Pass two numbers to add');
process.exit(1);
}
if(args.length <= 1){
console.log('We need two numbers to add them');
process.exit(1);
}
args.forEach((value) => {
result += parseInt(value);
});
console.log(`The sum of ${args[0]} with ${args[1]} is ${result}.`);
Running the app
node app.js 2 3
The result
The sum of 2 with 3 is 5.
I hope that you enjoy it, stay awesome!
Top comments (0)