May 28, 2021 08:06 by
Peter
You can get command-line arguments passed to your node.js application by using process.argv. process.argv is actually an array. So if you want values, out of this array you'll either have to use a loop or you can get simply by putting array index in process.argv.
Suppose you have a node.js app. "myscript.js".
You have passed parameters as:
$node myscript.js 4
Then in the code as in line number 2 of below code, we can get the parameter value as process.argv[2].
function GetSqrt() {
var num = process.argv[2];
console.log(" Number is " + num + " and its square " + num * num);
}
GetSqrt();
You might be thinking, why I have given index number 2 and not 0. Actually process.argv[0] will return 'node' and process.argv[1] will return your script name as in this case myscript.js.
If you have multiple arguments to pass from the command prompt, you can create a separate method for argument parsing as like
function GetSqrt() {
var args = ParseArguments();
args.forEach(function(num) {
console.log(" Number is " + num + " and its square " + num * num);
})
}
GetSqrt();
function ParseArguments() {
var input = [];
var arguments = process.argv;
arguments.slice(2).forEach(function(num) {
input.push(num);
});
return input;
}
Here arguments.slice(2) will remove first two arguments(node and your application name) from arguments array