Home » Node.js4 September 2018

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:

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

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

– Go to the directory where your index.js file is located.
– Run the following command in your terminal:

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.

– Run the command again in your terminal:

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

Write the following in your index.js file.

index.js

– Go to the directory where your index.js file is located.
– Run the following command in your terminal:

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.

Output:

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

Hope this helps. Thanks.

Node.js

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed