Accepting command line arguments is crucial when designing programs that allow a lot of interaction with the Node.js environment. Here in this blog, you will learn how to pass and receive command line arguments in a Node.js application.
What are Command Line Arguments?
Command Line Arguments refer to the passages that are typed into a command line interface system by a user to instruct the system on what to perform and how to do it.
Node.js Command line parameters are values submitted to a command when run from the terminal or the command interpreter. It is also important to note that all these arguments can be used in Node.js to tune up your script.
How to Pass Arguments?
Parameters are provided right after the script name if one decides to run the script in the terminal. For example:
node script.js arg1 arg2 arg3
Here:
Why Command Line Arguments Are Useful?
Command line arguments enable scripts to be used again and they make scripts dynamic in the way they can be changed. You can use them to:
Properties of arguments in Node.js
To analyze the command line arguments in a Node.js program, there is an array named as process.argv. The first two elements of this array are:
The actual arguments begin from the third element of the process.argv[2] and above.
Example Code
Here's an example script (arg2) that demonstrates how to receive and use command line arguments:
// It will allow one to access the arguments passed to the script
const args = process.argv.slice(2);
// Display the arguments
console.log('Command line arguments:', args);
// Example: Use arguments
if (args.length === 0) {
console.log('No arguments provided.');
} else {
console.log(`Hello, ${args[0]}!`);
}
Running the Script
To run the script, use:
node args.js John
Output:
Command line arguments: [ 'John' ]
Hello, John!
Parsing Arguments
For more detailed argument parsing the third party libraries should be used, such as yargs or commander. These libraries provide features like:
Command line arguments offer a highly effective way of making your Node.js programmes dynamic and customizable. Begin using process.argv today and if you need more complex features, look into the libraries yargs or commander.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our NodeJS Expertise.
0