Node.js: Pass Arguments/Parameters to Programs in Command Line

This article shows how you can pass command line arguments/parameters to any Node.js programs or .js file.

Here’s an example:


node index.js

This will execute the index.js file program.

Suppose, you can to pass some arguments and values to the index.js file program via command line. For example, in the below command, we are trying to pass a=20 and b=30


node index.js -a 20 -b 30

There are two ways to pass such arguments through command line.

1) Using the default process.argv property

The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched.

Write the following in your index.js file.

index.js


// printing each item of process.argv array
process.argv.forEach(function (val, index, array) {
  console.log(index + ': ' + val);
});
  • Go to the directory where your index.js file is located.
  • Run the following command in your terminal:

node index.js a 10 b=20 user user2

Output:

0: /usr/local/bin/node
1: /Users/mukeshchapagain/work/node/index.js
2: a
3: 10
4: b=20
5: user

In the output,

  • the first element is the path of the nodejs
  • and the second element is the path to the js file

So, the first two elements can be skipped.


// removing first two elements from the process.argv array
var argv = process.argv.slice(2);

// printing each item of the array
argv.forEach(function (val, index, array) {
    console.log(index + ': ' + val);
});
  • Run the command again in your terminal:

node index.js a 10 b=20 user user2

Output:

0: a
1: 10
2: b=20
3: user
4: user2

2) Using minimist node module

Minimist is the most popular module used to pass arguments to nodejs programs via command line.

This module makes it easy and user-friendly to work on passing the arguments and to fetch the passed argument values as well.

Install the module


npm install minimist

Write the following in your index.js file.

index.js


var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
  • Go to the directory where your index.js file is located.
  • Run the following command in your terminal:

node index.js -a 20 -b 30 --user user1

Output:

{ _: [], a: 20, b: 30, user: ‘user1’ }

You can pass the argument in two different ways:

– a single letter argument with a single hyphen before the argument like -a, -b, -u, etc.
– a multiple letter argument with a double hyphen before the argument like –user, –help, etc.

You can print each individual argument value as well.


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

console.log(argv.a)
console.log(argv.b)
console.log(argv.user)

Output:

{ _: [], a: 20, b: 30, user: ‘user1’ }
20
30
user1

Hope this helps. Thanks.