Open In App

Node.js process.argv Property

Last Updated : 08 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The process.argv in node is used to access and interact with the command-line arguments. It is an array that contains the command line arguments and helps user to interact node app using CLI.

Syntax:

process.argv

Return Value:

This property returns an array containing the arguments passed to the process when run in the command line.

  • process.argv[0]: is the process execution path
  • process.argv[1]: is the path for the js file.
  • process.argv[2] and more: other items in the array are the additional arguments passed by the user.

Below examples illustrate the use of process.argv property in Node.js:

Example 1: The below example uses process.argv property to display the CLI argument passed by the user.

JavaScript
// Node.js program to demonstrate the
// process.argv Property
 
// Include process module
const process = require('process');

// Printing process.argv property value
console.log(process.argv);

Command to run the code:

node index.js extra_argument1 extra_argument2 3

Output:

[ 'C:\\Program Files\\nodejs\\node.exe',
'C:\\nodejs\\g\\process\\argv_1.js',
'extra_argument1',
'extra_argument2',
'3'
]

Example 2: This example uses process.argv to display the total number of items in command and display each of them one by one.

JavaScript
// Node.js program to demonstrate the
// process.argv Property
 
// Include process module
const process = require('process');

// Printing process.argv property value
const args = process.argv;

console.log("number of arguments is "+args.length);

args.forEach((val, index) => {
    console.log(`${index}: ${val}`);
});

Command to run the code:

node index.js extra_argument1 extra_argument2 3

Output:

number of arguments is 5
0: C:\Program Files\nodejs\node.exe
1: C:\nodejs\g\process\argv_2.js
2: extra_argument1
3: extra_argument2
4: 3

Note: The above program will compile and run by using the node filename.js command followed by arguments.

Summary

The process.argv property is an inbuilt application programming interface of the process module which is used to get the arguments passed to the node.js process when run in the command line.

Reference: https://nodejs.org/api/process.html#process_process_argv


Next Article

Similar Reads