Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
process.argv() Method in Node.js
The process.argv property returns an array containing command-line arguments passed when the Node.js process was launched. The first element is the path to the Node.js executable, and the second is the path to the JavaScript file being executed.
Syntax
process.argv
Parameters
process.argv is a property, not a method, so it doesn't take any parameters. It automatically captures all command-line arguments passed to the Node.js process.
Basic Usage Example
Create a file named argv.js and run it using the command node argv.js:
// Node.js program to demonstrate the use of process.argv // Printing process.argv property value console.log(process.argv);
[ '/usr/bin/node', '/home/node/test/argv.js' ]
Processing Arguments
Let's examine each argument and count the total number:
// Node.js program to demonstrate process.argv processing
var args = process.argv;
console.log("Total number of arguments: " + args.length);
args.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
Total number of arguments: 2 0: /usr/bin/node 1: /home/node/test/argv.js
Accessing Custom Arguments
Command-line arguments passed after the script name start from index 2. Run with: node argv.js hello world 123
// Accessing custom command-line arguments
const customArgs = process.argv.slice(2);
console.log("Custom arguments:", customArgs);
if (customArgs.length > 0) {
console.log("First custom argument:", customArgs[0]);
} else {
console.log("No custom arguments provided");
}
Custom arguments: [ 'hello', 'world', '123' ] First custom argument: hello
Argument Structure
| Index | Contains | Example |
|---|---|---|
| 0 | Node.js executable path | /usr/bin/node |
| 1 | Script file path | /home/user/script.js |
| 2+ | Custom arguments | User-provided values |
Conclusion
process.argv is essential for building command-line Node.js applications. Use process.argv.slice(2) to access custom arguments passed by users, enabling flexible script behavior based on input parameters.
