Hello friends, In this article I will show you a simple program to pass the parameters to Node.JS from Console. And we will get the values of the parameters passed in the JavaScript file. The code written in JavaScript can use the parameters passed from the Node.JS console.
How to pass the parameters to Node.JS from Console
In the code below I have written a small code snippet. In the code I am passing multiple parameters to the NodeJS file.
node program.js 10 20 30 40
For the above code snippet I am passing 10, 20, 30 and 40 as the input parameters to the program.js file in the console.
How to get the parameter values from console in NodeJS
Below code is used to collect the parameters values passed to the NodeJS. This code can be placed in program.js which I have used in above code snippet.
var book = require("./grades").book; for (var i = 2; i < process.argv.length; i++) { book.add(parseInt(process.argv[i])); } console.log(book.getAverage());
The code gets the reference off grades.js file present in the same folder. I will share the code of the file in the later part of the article.
Finally we have to use process.argv to collect the parameters. I am starting from i =2 as process considers ‘node’ and ‘program.js’ as the parameters.
And since my ‘addGrades’ expects the parameters in Int, I am parsing the parameters to Integer type.
Now coming to the ‘grades.js’ file’s code.
var grades = { _grades : [], add: function(newGrade){ this._grades.push(newGrade); }, getAverage: function(){ var count = 0; for(var i = 0; i < this._grades.length; i++) { count = count + this._grades[i]; } return count/this._grades.length; } }; exports.book = grades;
In the above I have create an JavaScript object named grades. This object has multiple methods and private integer array.
As per the JavaScript naming convention followed by developers, I have names the private array starting with “_” underscore.
Most of the methods are self explanatory. And I am finally exporting the object to the module named book.
My program calculates the average of the numbers passed to the program.js as input parameters. Finally calculates the average.
For further Reading in Node.JS Series:
Writing my first Hello World program in Node JS
Simple Trick to create a NodeJS Server on Windows/Ubuntu
Parsing the Query String, HTTP Method, request Path and payload for NodeJS
Leave a Reply