Node.js: working with command line arguments

When we execute Node.js from the command line we can pass arguments to the node command.

Node.js memorizes command line arguments in the process.argv array. When we execute the following file:


'use strict';

const echo = console.log;

let args = process.argv;

args.forEach((arg, index) => {
    echo('Argument ' + index + ': ' + arg);
});

in this way:


node arguments.js test

we get:


Argument 0: /usr/local/bin/node
Argument 1: /home/user/arguments.js
Argument 2: test

It's a common mistake to think that the actual argument of our script is the first element in the array. Instead, it's the third element in the array at index 2.

Consequently, the arguments passed to arguments.js start from the third element. Arguments are all of the type String. Node.js doesn't provide the validation and retrieving methods of other programming languages such as Java.

In order to validate command line arguments, you should always make sure that actual arguments are present:


'use strict';

let args = process.argv;

if(args.length >= 3) {
   // At least 1 actual argument
}

Then we can validate the argument's format:


'use strict';
const validator = require('validator');

let args = process.argv;

if(args.length >= 3) {
   let arg = args[2];
   if(!validator.isInt(arg)) {
       throw new Error('Integer required!');
   }
}

validator works only with strings, so it's the best candidate for arguments validation.

If the argument's format doesn't match our criteria, the best thing to do is to raise an error and stop the script's execution. Otherwise we can't go further.

Prev Articles Next