How Can I Send Command Line Arguments To A Node.js Program In JavaScript?

To pass command line arguments to a Node.js program, you can access them using the process.argv property.

Here’s an example of how you can access command line arguments in a Node.js program:

// app.js

From the command line, you can pass arguments after the node command and the app name, separated by spaces. For example:

$ node app.js arg1 arg2 arg3

The process.argv array contains the following elements:

  • process.argv[0]: The path of the Node.js executable.
  • process.argv[1]: The path of the JavaScript file being executed (in this case, app.js).
  • process.argv[2] and onwards: The command line arguments you passed.

In the example above, process.argv[2] will be arg1, process.argv[3] will be arg2, and process.argv[4] will be arg3.

You can access the command line arguments within your program like this:

// app.js
console.log('Command line arguments:', process.argv.slice(2));

This will log an array containing only the command line arguments, without the executable and file path parts.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!