Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 7, 2022 12:44 pm GMT

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]);

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

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}`);});

Let's run the script with the following command:

node script.js hi there devs

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/node1: /Users/bobby/dev/script.js2: hi3: there4: devs

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


Original Link: https://dev.to/bobbyiliev/how-to-pass-command-line-arguments-to-a-nodejs-app-5294

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To