DEV Community

Cover image for How to Pass an Argument in Nodejs Command Line Application
Jason V. Castellano
Jason V. Castellano

Posted on • Updated on

How to Pass an Argument in Nodejs Command Line Application

For those software engineers who have a lot of responsibilities the terminal is their home. It's very satisfying to create your own command line by using your favorite programming language. In this post, let me show you how to create a command line application using nodejs.

But before anything else. You need to install NodeJs. If your NodeJS are not install yet. You can download it here.

Now, let us start.

Lets create your index.js file in your folder. Then inside index.js. type this code.

Image description

Now, you can open your terminal and run it.

node index FirstArgument // output: FirstArgument
Enter fullscreen mode Exit fullscreen mode

As you can see the process.argv[2] is an array. Let us discuss some of the array of arguments below:

process.argv[0] - is path where nodejs is located. In my case it is /usr/local/bin/node

process.argv[1] is a path where my index file is located. In my case it is /home/thegreytangent/Desktop/dev.to/index

process.argv[2] it is first argument on my script: FirstArgument

process.argv[3] - the second argument and so on.

What if you need all the arguments? No need to worry just loop it.

Image description

Now, run it in your terminal.

node index FirstArg SecondArg ThirdArg

The expected output should be:

Argument number: 0: /usr/local/bin/node
Argument number: 1: /home/thegreytangent/Desktop/dev.to/index
Argument number: 2: FirstArg
Argument number: 3: SecondArg
Argument number: 4: ThirdArg
Enter fullscreen mode Exit fullscreen mode

That's all for today!

In this post, we learn to add arguments in our nodejs CLI. Thanks for reading. You can leave a like or a share if it is helpful and ask any questions in the comments below. (-:

Top comments (0)