English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

Other NodeJS

Node.js Command Line Arguments

Node.js Command-line Arguments

To access command-line arguments in the Node.js script file, use the process.argv array, which contains the command-line arguments passed when starting the Node.js process.

When your program is so summarized, command-line arguments are usually used, and you need to send some values to make the program run. A simple example is a summation calculator that adds two numbers. You need to provide two numbers as arguments. Another example is loading a configuration file. When you start the Node.js process, you will provide this configuration file to start the application in one of the required modes.

Example

In this Node.js tutorial, we will learn how to access Node.js command-line arguments with examples.

// process.argv is an array containing command-line arguments
// Use forEach to print all parameters
process.argv.forEach((val, index) => { 
  console.log(`${index}: ${val}`); 
 });

Node Output

~$ node command-line-args-example.js argument_one argument_two 3 4 five
0: /usr/local/nodejs/bin/node
1: /home/w3codebox/workspace/nodejs/command-line-args-example.js
2: argument_one 
3: argument_two 
4: 3
5: 4
6: five

By default, parameter 0 is the path to the Node program, and parameter1Is the path to the Node Java script file. The rest are other parameters provided to Node.js. Space characters are considered as delimiters for parameters.

Conclusion:

In this Node.js tutorial, we learned how to provide and access command-line arguments in Node.js script files.