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.
It is important to include the process module in a require statement. This is how we can access the argv
property upon the process.
for
-loop to iterate over the indexes of the process.argv
array. Then we print out each argument and its index.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
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.