How to Parse Command Line Arguments in Node ?
Last Updated :
16 Sep, 2024
Command-line arguments, in the context of a command-line interface (CLI), are text strings that provide extra information to a program when it is executed.
In Nodejs, these arguments are accessible through an array known as argv (arguments values), where the shell passes all received command-line arguments to the running process.
Approach
To parse the command line arguments in node js, we can use two methods to parse command-line arguments via process.argv array as well as popular package yargs.
Method 1: Using process.argv
The most straightforward method to access command-line arguments in Node.js is through the `process.argv` array. This array is exposed by Node.js for each running process. The first element of `process.argv` is the file system path to the Node executable file, the second element is the path to the currently executing JavaScript file, and the subsequent elements constitute the arguments provided via the command line.
Note: The first two elements of process.argv array are always present even if we don’t pass any arguments.
Example 1: Below is the example to show the usage of process.argv:
JavaScript
for (let i = 0; i < process.argv.length; ++i) {
console.log(
`index ${i}
argument ->
${process.argv[i]}
`
);
}
Run the gfg.js file using the following command by passing arguments:
node gfg.js I Love GeeksforGeeks
Output:

Using process.argv
Example 2: Program to perform an arithmetic operation according to the arguments passed via cmd.
JavaScript
// To trim first 2 elements
const arg = process.argv.slice(2);
arg[1] = Number(arg[1]);
arg[2] = Number(arg[2]);
switch (arg[0]) {
case '+':
console.log(`Result of ${arg[1]}
+ ${arg[2]} = ${arg[1] + arg[2]}`);
break;
case '*':
console.log(`Result of ${arg[1]}
* ${arg[2]} = ${arg[1] * arg[2]}`);
break;
case '-':
console.log(`Result of ${arg[1]}
- ${arg[2]} = ${arg[1] - arg[2]}`);
break;
case '/':
if (arg[2] == 0) {
console.log(
'cannot be divided by zero!!');
} else {
console.log(`Result of ${arg[1]}
/ ${arg[2]} = ${arg[1] / arg[2]}`);
}
break;
case '%':
if (arg[2] == 0) {
console.log(
'cannot be divided by zero!!');
} else {
console.log(`Result of ${arg[1]}
% ${arg[2]} = ${arg[1] % arg[2]}`);
}
break;
default: console.log(
`operation cannot be performed!!`);
}
Steps to run the arithmetic.js file by passing the following arguments:
Output:

Program to perform the arithmetic operation according to the arguments passed via cmd.
Method 2: Using yargs module
Passing arguments via cmd becomes tedious when we start working with flags or if your server needed a lot of arguments.
app -h host -p port -r -v -b --quiet -x -o outfile
To solve this, we can use the third library module such as yargs to parse the arguments passed via cmd. In this module, you can pass arguments as a key-value pair and later access them with the help of a key. The .argv gets the arguments as a plain old object.
Install yargs module using the following command:
npm install yargs --save
The updated dependency in packaga.json file:
"dependencies": {
"yargs": "^17.7.2"
}
Example: Below is the example to show the usage of yargs module:
JavaScript
const args = require('yargs').argv;
console.log(args);
console.log(`Language : ${args.language}`);
console.log(`IDE : ${args.ide}`);
To run the file, execute the following command:
node yarg.js --language=javascript --ide=GFG_IDE command1 command2 --b --v
Output:

Using yargs module
Note:
- argv.$0 contains the name of the script file which is to execute.
- argv._ is an array containing each element not attached to an option(or flag) these elements are referred to as commands in yargs.
- The flags such as argv.time, argv.b, etc become the property of the argv. The flags must be passed as –flag. Example: node app.js –b
Conclusion
Using command-line arguments in Node.js, either through the process.argv array or the yargs module, enhances script functionality by allowing flexible input handling and easy parameter parsing.
Similar Reads
How to Read Command Line Arguments in Node ?
Command-line arguments (CLI) consist of text strings utilized to provide extra information to a program during its execution via the command line interface of an operating system. Node facilitates the retrieval of these arguments through the global object, specifically the process object. ApproachTo
2 min read
How to print command line arguments passed to the script in Node.js ?
Node.js is an open-source and cross-platform runtime environment built on Chrome's V8 engine that enables us to use JavaScript outside the browser. Node.js helps us to use build server-side applications using JavaScript. In Node.js if you want to print the command line arguments then we can access t
2 min read
Command Line Arguments in Golang
Command-line arguments are a way to provide the parameters or arguments to the main function of a program. Similarly, In Go, we use this technique to pass the arguments at the run time of a program. In Golang, we have a package called as os package that contains an array called as "Args". Args is an
2 min read
Command Line Arguments in Objective-C
In Objective-C, command-line arguments are strings of text that are passed to a command-line program when it is launched. They can be used to specify options or parameters that control the behavior of the program or to provide input data that the program can process. To access command-line arguments
2 min read
Sending Command Line Arguments to NPM Script
In the sector of NodeJS development, NPM (Node Package Manager) scripts are a effective tool for automating numerous tasks like strolling exams, building the mission, or starting a improvement server. However, there are times while you need to bypass arguments to these scripts to customize their beh
3 min read
Bash Script - How to use Command Line Arguments
In this article, let us see about Command Line Arguments usage in Bash script. Arguments are inputs that are necessary to process the flow. Instead of getting input from a shell program or assigning it to the program, the arguments are passed in the execution part. Positional Parameters Command-line
4 min read
Command Line Arguments in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
6 min read
How to Open Node.js Command Prompt ?
Node.js enables the execution of JavaScript code outside a web browser. It is not a framework or a programming language, but rather a backend JavaScript runtime environment that allows scripts to be executed outside the browser. You can download Node.js from the web by visiting the link "Download No
2 min read
How to Get POST Data in Node ?
Handling POST data is a fundamental aspect of developing web applications and APIs using Node.js. POST requests are used when a client needs to send data to the server, such as submitting form data, uploading files, or sending JSON payloads. This article will cover various methods to retrieve and ha
4 min read
How to kill all instances of a Node.js process via command line ?
To kill all instances of a Node.js process via the command line, use the command killall node on the Mac or Unix-based systems. This terminates all running Node.js processes. Why we need to kill all the instances?Sometimes there may be some issue with the NodeJS like the server is listening to some
2 min read