Sunday, October 14, 2018

How to pass command line argument in node js

             How to pass command line arguments in node js


Many times we need to pass command line arguments in a program. In node js program is like an another program written in java script.  Following is the simplest way to pass command line argument.

Here is Document for Nodejs API to get command line arguments.  There is a top level variable called process. Variable having settings for the process. When a NodeJs program starts it have the list of command line arguments in process.argv.

Following is code for displaying all command line arguments.


process.argv.forEach((val, index) => { console.log(`${index}: ${val}`);});

If program named cmdLineArg.js is executed with following command line argument,

$ node cmdLineArg.js Arg1 Arg2 Arg3

Output:
0: /usr/bin/node
1: /home/nodeExample/cmdLineArg.js
2: Arg1
3: Arg2
4: Arg3

The list of arguments start with index zero and last index is one less than the total number of argument. Following is the meaning of each argument.

0 : Path of NodeJs installation. This can be verified by "which node" command on linux.
1: Program name with absolute path.
2 : First argument passed to the Node js program.
3: Third argument.
4. Fourth argument.

No comments:

Post a Comment

install node js npm linux

                    How to install NodeJs and NPM on Linux ? Before using a node js program. It has to be installed on a operating sys...