When an application is run through the command-line interface (CLI) of an operating system, the Command-line arguments are used to pass additional information to a program . In Node.js, all command-line arguments received by the shell are given to the process in an array called argv(arguments-values).
You can pass command line arguments to a Node.js program by using the process.argv array.
The process.argv array contains the command line arguments passed to the Node.js process. The first element of the array (process.argv[0]) is the path to the Node.js executable, and the second element (process.argv[1]) is the path to the JavaScript file being executed. The remaining elements of the array are the command line arguments.
Here's an example program that prints the command line arguments:
// Print the command line arguments
console.log(process.argv);
If you run this program with the command node index.js arg1 arg2 arg3, it will output the following array:
[ 'path/to/node', 'path/to/index.js', 'arg1', 'arg2', 'arg3' ]
You can access the individual command line arguments by indexing into the process.argv array. For example, to access the second argument (arg2) in the example above, you would use process.argv[3].
Note that the first two elements of the process.argv array are not usually relevant to the program's logic, so you will usually want to start reading the arguments from index 2 (process.argv[2]).
Comments (0)