How do I pass command line arguments to a Node.js program and receive them?

Better Stack Team
Updated on March 11, 2024

In Node.js, you can pass command line arguments to your script the same as you would for any other command line application. Simply type your arguments after the script path separated with a space as shown below:

node task.js foo bar

Then you can retrieve the arguments from the process.argv array like this:

process.argv.forEach((val, index) => {
  console.log(index + ': ' + val);

The first element (index 0) is always a path to your Node.js executable and the second element (index 1) is a path to your script. Additional elements are the ones you pass when executing the script. In the case of the example above. The process.argv array would look something like this:

0: /path/to/node
1: /path/to/task.js
2: foo
3: bar

You can also use packages such as commander, yargs or minimist to help you handle and parse command line arguments.

Remember, command line arguments are string so you need to convert them to other types when necessary.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github