a blog for those who code

Monday 4 May 2015

Pass command line arguments in NodeJS

In this post we are going to learn about how to pass command line arguments in NodeJS. It is possible to pass some values from the command line to your NodeJS application when the application is executed. These values are called Command Line Arguments and sometimes they are important when you want to control your program from outside the application.

There are number of ways you can pass command line arguments in your NodeJS application and they are :

1. Using process.argv

According to Nodejs.org, process.argv is an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

Example : If you have a JavaScript file as example2.js having the contents as

process.argv.forEach(function(val, index, array) {
console.log(index + ' : ' + val);
});

So when you run the the file using node example2.js a b c d you will get an output as

0 : node
1 : D:\example\example2.js
2 : a
3 : b
4 : c
5 : d

2 . Using yargs module

Accoding to yargs, it is a light-weight option parsing with an argv hash. You need to install yargs by npm install yargs. Lets say you have a JavaScript file as example2.js having contents as

var argv = require('yargs').argv;
console.log('First : ' + argv.first);
console.log('Second : ' + argv.second);

So when you run the file using the command node example2.js --first=5 --second=10 you will get an output as :

First : 5
Second : 10

3. Using minimist module

According to minimist, it is module which parse argument options. You need to install minimist by npm install minimist. Lets say you have a JavaScript file as example2.js having contents as

var argv = require('minimist')(process.argv.slice(2));
console.log(argv);

So, when you run the file using the command node example2.js -a hello -b world you will get an output as : { _: [], a: 'hello', b: 'world' }


Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment