nodejs command line arguments

Node.js Command Line Arguments

To pass command line arguments in Node.js, you can access them through the process.argv array. The process.argv array contains the command line arguments passed to the Node.js script. Here's how you can use command line arguments in Node.js:

  1. The first element of the process.argv array is the path to the Node.js executable.
  2. The second element is the path to the JavaScript file being executed.
  3. The subsequent elements are the command line arguments passed to the script.

For example, if you have a Node.js script called script.js and you run it with the following command:

node script.js arg1 arg2 arg3

The process.argv array will be:

[
  '/path/to/node',
  '/path/to/script.js',
  'arg1',
  'arg2',
  'arg3'
]

You can access the command line arguments by indexing into the process.argv array. For example, to access the first argument (arg1), you can use process.argv[2].

Note: The first two elements of the process.argv array are not part of the command line arguments passed to the script. They represent the Node.js executable and the path to the script file.

Here's an example of a Node.js script that prints the command line arguments:

// script.js
for (let i = 2; i < process.argv.length; i++) {
  console.log(`Argument ${i - 1}: ${process.argv[i]}`);
}

When you run this script with the command node script.js arg1 arg2 arg3, it will output:

Argument 1: arg1
Argument 2: arg2
Argument 3: arg3

That's how you can use command line arguments in Node.js.