3

How to Pass Command-Line Arguments in Node.js (2022)

 2 years ago
source link: https://blog.bitsrc.io/how-to-pass-command-line-arguments-in-node-js-46af7960b45f
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Pass Command-Line Arguments in Node.js (2022)

In this article, I want to show how to pass command-line arguments in your Node.js application.

Command-Line
Photo by Pankaj Patel on Unsplash

No Libraries needed!

The process.argv property returns an array containing the command-line arguments passed when the Node.js process was launched. The first element will be process.execPath.

See process.argv0 if access to the original value of argv[0] is needed.

The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command-line arguments.

Let’s start with an example!

First, you need to create a new file called index.js in whatever directory. After you’ve created the file, add the content below.

index.js

So what we basically do is, iterate through a list of strings which are basically all arguments.

  • Element of index 0 will always be taken by the location of your current Node bin on your machine.
  • Element of index 1 will be always the location of your executed file, the so-called entry point.

Now you can run the following command in your terminal. Keep in mind, you need to be at the same directory where your index.js file is placed.

$ node index.js foo=bar hello world

The output in your console should be look something like this:

0 /usr/local/Cellar/node@14/14.18.3/bin/node
1 /Users/kevin/Workspace/index.js
2 foo=bar
3 hello
4 world

Very simple, right? Thanks for reading my short article on how to pass command-line arguments in Node.js. I hope, I could refresh your knowledge, or even better, you did learn something new.

If you have any questions, please don’t hesitate to reach out in the comments.

Cheers!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK