Command Line Arguments in Nodejs


process.argv is a property in Node.js that contains an array of command-line arguments passed to the Node.js process when it was launched.

  • The first element of the process.argv array is always the path to the Node.js executable.
  • The second element is always the path to the JavaScript file being executed.
  • The subsequent elements of the array are any additional command-line arguments passed to the program.

For example, if you run the following command in the terminal:

node process_args.js Joes

The process.argv array would be:

[ '/path/to/node.exe', '/path/to/app.js', 'Joes']

You can use process.argv to access and process command-line arguments in your Node.js program. This is a Node.js program that retrieves the third element of the process.argv array (index 2) and assigns it to the nameArg variable. If there is no third element, it defaults to the string 'world'. Then, the program uses string interpolation to output a message to the console, which includes the value of nameArg.

For example, if you run the following command in the terminal:

node app.js Joes

The output would be:

Hello Joes!

If you run the following command instead:

node app.js

The output would be:

Hello world!

This program is a simple example of how to use command-line arguments in a Node.js program to customize its behavior.