DEV Community

Cover image for How to pass command line arguments to a Node.js app?
Bobby Iliev
Bobby Iliev

Posted on • Originally published at devdojo.com

How to pass command line arguments to a Node.js app?

Introduction

Similar to a Bash script where you can pass arguments to a script using the $1 syntax, you can also pass arguments to a Node.js app.

In this quick tutorial, you will learn how to pass arguments to a Node.js app using the process.argv array.

Prerequisites

Before you get started, you will need to have Node.js installed:

Pass arguments to a Node.js app

Let's start by creating a new file called script.js and adding the following code to it:

const process = require('process');

console.log(process.argv[2]);
Enter fullscreen mode Exit fullscreen mode

A quick rundown of the process.argv array:

  • process.argv[0] is the path to the Node.js executable
  • process.argv[1] is the path to the script file
  • process.argv[2] is the first argument passed to the script
  • process.argv[3] is the second argument passed to the script and so on

Let's run the script with the following command:

node script.js DevDojo

# Output:
DevDojo
Enter fullscreen mode Exit fullscreen mode

Printing all arguments

To print all arguments, you can use a forEach loop just as you would with a standard array:

const process = require('process');

process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});
Enter fullscreen mode Exit fullscreen mode

Let's run the script with the following command:

node script.js hi there devs
Enter fullscreen mode Exit fullscreen mode

We are now passing 3 arguments to the script and in this case, the output of this script will be:

0: /opt/homebrew/Cellar/node@16/16.16.0/bin/node
1: /Users/bobby/dev/script.js
2: hi
3: there
4: devs
Enter fullscreen mode Exit fullscreen mode

Conclusion

This is pretty much it! I hope that you find this useful!

In case you are new to Node.js I could suggest the following tutorial on how to get started:

How To Write Your First Node.js Script

To learn more about arguments in Bash scripts, you can read the following article:

Bash Scripting Tutorial

Latest comments (2)

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
mhcrocky profile image
mhcrocky

amazing words!