DEV Community

Cover image for Node.js, Accept arguments from the command line
Jose Tandavala
Jose Tandavala

Posted on

Node.js, Accept arguments from the command line

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
Enter fullscreen mode Exit fullscreen mode

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}`);
});
Enter fullscreen mode Exit fullscreen mode

You can get only the additional arguments by creating a new array that excludes the first 2 params:

const args = process.argv.slice(2);
Enter fullscreen mode Exit fullscreen mode

This said consider the below snippet

const args = process.argv.slice(2);
console.log(args);
Enter fullscreen mode Exit fullscreen mode

We can execute this program now

node app.js jose
Enter fullscreen mode Exit fullscreen mode

Here is the result

jose
Enter fullscreen mode Exit fullscreen mode

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}.`);
Enter fullscreen mode Exit fullscreen mode

Running the app

node app.js 2 3
Enter fullscreen mode Exit fullscreen mode

The result

The sum of 2 with 3 is 5.
Enter fullscreen mode Exit fullscreen mode

I hope that you enjoy it, stay awesome!

Top comments (0)