Passing parameters to the application in Nodejs

When launching an application from the terminal/command line, we can pass parameters to it. The process.argv array is used to receive parameters in the application code . This is similar to how in C/C++/C#/Java languages, a set of arguments in the form of a string array is passed to the main function.

The first element of this array always points to the path to the node.exe file that the application is calling. The second element of the array always points to the path to the application file that is being executed.

For example, let’s define the following app.js file :

let nodePath = process.argv[0];
let appPath = process.argv[1];
let name = process.argv[2];
let age = process.argv[3];

console.log("nodePath: " + nodePath);
console.log("appPath: " + appPath);
console.log("name: " + name);
console.log("age: " + age);

In this case, we expect two parameters to be passed to the application: name and age.

Now let’s run the application with the following command:

node app.js Tom 45

In this case, “Tom” and “45” are the values ​​that are placed in process.argv[2] and, respectively process.argv[3]: