Argv. Often Node.js programs are used to render web pages, but they can be used on the command line. And with process.argv, we can receive command-line arguments.
It is important to know that the first arguments in this array are the name of the node program, and the script name. The arguments that follow were specified on the command-line.
Example. It is important to include the process module in a require statement. This is how we can access the argv property upon the process.
Part 1 We use a for-loop to iterate over the indexes of the process.argv array. Then we print out each argument and its index.
Part 2 We can access the important arguments—those that come after the file names—by starting at index 2.
const process = require("node:process");
// Part 1: loop over all arguments and print them.
for (var i = 0; i < process.argv.length; i++) {
let argument = process.argv[i];
console.log("Argument", i, "=", argument);
}
// Part 2: loop over arguments at indexes 2 and higher for important arguments.
for (var i = 2; i < process.argv.length; i++) {
console.log("Important argument:", argv[i]);
}node.exe programs/program.js test one twoArgument 0 = C:\Program Files\nodejs\node.exe
Argument 1 = C:\Users\...\Documents\programs\program.js
Argument 2 = test
Argument 3 = one
Argument 4 = two
Important argument: test
Important argument: one
Important argument: two
Summary. Node programs can receive arguments like any other console program. And with the process module, we can access the argv array to handle these arguments.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.