NPM, an abbreviation for Node Package Manager, is the default one for the JavaScript runtime environment Node.js. With more than 800,000 code packages, it’s one of the largest Software Registry available in the world. NPM is a command-line utility to interact with the repository for package installation. You can also use NPM for version management and dependency management.
The best part is it’s free to use, and anyone can download the software program available in the NPM public library without registration. If you are new to NPM and do not know much about it, this article will help you handle node command-line arguments. Here we will explain all the nitty gritty of NPM argument flags and vectors. Also, the article will help you with the use of the Commander.
Check out to know more about handling NPM arguments.
Prerequisites of NPM Command-line Argument h2
Before you start handling the Node.js command-line arguments, you must install Node.js on your system. Once you have that, you are set to proceed further with the Node command line Arguments.
For more information about Node.js and how to handle node.js command-line arguments, check out Node.js complete course.
Argument Vectors
An argument vector in Node.js allows the passing of a list of arguments. It is an array accessible via process.argv. All of the parameters supplied to the script are stored in the array. The node arguments include the Node.js executable and the script’s path, as well as the filename.
If you run the following command,
node example.js -a -b -c The argument vector will contain the following five items, [ '/usr/bin/node', '/path/to/example.js', '-a', '-b', '-c' ]
Even if you execute a script without any arguments, the array will still include the script file and the node executable that you have run.
The number of arguments handed in is often indicated by an argument count (argc) along with the argument vector. To get the length of the argument vector array, we can use a Node.js function like the following:
if (process.argv.length === 2) { console.error('Expected at least one argument!'); process.exit(1); }
The example code that we have mentioned here can check the length of argv. Length 2 shows that only the executable node and the script file are available. Without arguments, it would have shown the message ‘Expected at least one argument’ and ‘exit’.
Argument Flags
Let’s have a look at an example that demonstrates how to show a default message in node command-line arguments. Nevertheless, in the event that a certain flag is present, it will show a different message.
if (process.argv[2] && process.argv[2] === '-f') { console.log('Flag is present.'); } else { console.log('Flag is not present.'); }
This script determines whether or not our argument vector has a third item by checking for its presence. The index is set to 2 due to the fact that arrays in JavaScript employ a zero-based indexing system. The output will be changed if there is a third item that is present, and it is equivalent to -f.
Below you can check an example where a script has been run without an argument:
node example.js
Now the output that is generated from there looks like this:
Output
Flag is not present.
However, if you run the script with arguments, it will look like the below:
node example.js -f
In that case, the output will be as follows:
Output
Flag is present.
Other than restricting ourselves only in altering the conditional control structure; we may make use of the actual value that has been passed on to the script:
const custom = (process.argv[2] || 'Default'); console.log('Custom: ', custom);
This script does not include a conditional dependent on the argument; rather, it uses the value provided in (which, if the argument is not there, is set to “Default”) and inserts this into the script output.
Also, check out the article how to export Node.js modules using exports.
Arguments with Values
In this section, we have explained npm script arguments that accept arguments along with values. It will help to understand the situations where you use a value and an argument together.
It will look like the following if you accept multiple arguments:
// Check to see if the -f argument is present const flag = ( process.argv.indexOf('-f') > -1 ? 'Flag is present.' : 'Flag is not present.' ); // Checks for --custom and if it has a value const customIndex = process.argv.indexOf('--custom'); let customValue; if (customIndex > -1) { // Retrieve the value after --custom customValue = process.argv[customIndex + 1]; } const custom = (customValue || 'Default'); console.log('Flag:', `${flag}`); console.log('Custom:', `${custom}`);
Since we are not depending on specific index values but rather on indexOf, we can search for the arguments in the argument vector in whatever order we want, without thinking of where they are located.
Now, you can check the example below to know how it looks like to run a script without arguments:
node example.js
The output looks like:
Output
Flag: Flag is not present.
Custom: Default
However, it will look like following if you run a script with the arguments:
node example.js -f --custom Override
The output is
Output
Flag: Flag is present.
Custom: Override
This is how the command-line script can accept more than one argument and value.
Using Commander
The examples that we have mentioned above work without any hindrance when we specify the argument input. However, you can try using arguments with or without equal signs (as -nJaneDoe or –name=JohnDoe). Not only that, but you can also use quoted strings to pass in the values with spaces, e.g. -n “Jane Doe”. In that case, as well you can have alias arguments that offer both longhand and short versions.
This is where the commander library comes in handy. It’s one of the most useful Node.js libraries.
As you use custom parameters along with named variables, you can keep your NPM scripts compact. However, going through the Node.js certification training can help you understand node command-line arguments in depth.
Check out the descriptions below to understand how to use Commander.
As the very first step, go to your project directory and start initializing the projects:
npm init
Now, install the NPM commander:
npm install commander@7.2.0
Here, we will take our previous example to use it on Commander:
const commander = require('commander'); commander .version('1.0.0', '-v, --version') .usage('[OPTIONS]...') .option('-f, --flag', 'Detects if the flag is present.') .option('-c, --custom <value>', 'Overwriting value.', 'Default') .parse(process.argv); const options = commander.opts(); const flag = (options.flag ? 'Flag is present.' : 'Flag is not present.'); console.log('Flag:', `${flag}`); console.log('Custom:', `${options.custom}`);
Commander is responsible for all of the heavy work, including the processing of process.argv and the addition of the arguments and any values connected with them as properties in our commander object.
Our script can be simply versioned, and the version number can be reported using either the -v or –version argument. We also receive some helpful output that explains the usage of the script by supplying the –help argument, and if you pass an argument that isn’t defined or is without a specified value, it will report an error.
Conclusion
While concluding, we would like to mention that learning the Node.js framework can be crucial to your career as a full-stack developer. You may try a full-stack web developer course with placement to have complete knowledge of the topic and get hired by the top brands in the world.
That’s all. Hope you find the article helpful. Now you know all the basics of argument vectors and how to detect argument flags. Also, you can easily understand how to handle more than one value and argument. However, if you want to know more about Node.js or how to handle node.js command-line arguments, you must check out the Knowledgehut’s Node.js complete course.
Frequently Asked Questions (FAQs)
1. What is an argument in Node.js?
Within the context of every function call, there is a unique construct known as the arguments object. It’s quite similar to an array-like object. The list of arguments that were parsed while calling the function is included inside the node args variable.
It has a length property that is equivalent to the total number of arguments that were supplied into the function. These values may be accessed by indexing into the array; for example, arguments[0] represent the first parameter in the array.
2. How is an argument passed in Node.js?
If you are trying to run any simple command-line interface task, passing in arguments comes as a very basic requirement. All command-line arguments that are accepted by the shell in Node.js, as well as in C and many other environments that are similar, are supplied to the process in an array that is called argv (which is short for “argument values”). Node.js provides this array in the form of a process.argv for each running process.
Have a look at the example below to understand it better.
First create a file named as argv.js and add the following line,
console.log(process.argv);
Then, save and try the below mentioned in your shell,
$ node argv.js one two three four five [ 'node', '/home/avian/argvdemo/argv.js', 'one', 'two', 'three', 'four', 'five' ]
Now you can check the array as it contains all the arguments that you have passed in.
3. What happens if I perform a node command without any argument?
If you take a look at the above, The first two elements are -node and the path to your script. Even if the program does not take any arguments of its own, the script interpreter and path is considered as the arguments to the shell.
4. What is a command-line argument?
After providing the name of the node.js program during the program’s execution, the information sent through to be processed is known as a command-line argument. These arguments are then saved as Strings in a String array before being sent to the main() function to be processed. These command-line arguments may serve as input for the node.js application we are working on.
Discussion about this post