LEARNNode CLI Automation

Node.js Process Arguments – Part #1

This is a two article series on Node.js Process Arguments. You can find these two articles below:

For a production quality CLI, you would need to provide a lot of features like using flags to fire certain functions or taking arguments from the terminal. This is where the Node.js process comes into the picture. Let's take a look at it.

Working With Arguments

Node.js global process object has a property called argv which returns an array containing the command line arguments when the Node.js process was launched.

The first element in this argument array is the execution path. The second element will be the path of the JavaScript file being executed. The remaining elements will be any additional command-line arguments.

Let's take an example. I have created an index.js file and have the following code inside it:

// print process.argv
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});

And now I am going to run this file with the following command:

node index.js one check=true false

I will get an output like this:

0: /usr/local/bin/node
1: /Users/ahmadawais/node/process-args.js
2: one
3: check=true
4: false

Wrapping Up

This is how you can use the process.argv property to get all the arguments from the command-line. So if you need to add any flags in your CLI, you can just go ahead and use this property.

Posted by Saad (It's a work in progress: Needs copy editing review by Awais.)