Let's create a simple calculation module which performs the addition, subtraction, multiplication and division of two numbers to the console.
As we know that in node app, module has a separate js file. So we'll create a calculate.js into application root.
calculate.js
var cal = {
add: function (a1,a2) {
var add = a1 + a2
console.log('Add: ' + add+'\n');
},
minus:function (s1, s2) {
var minus = s1 - s2
console.log('Minus: ' + minus+'\n');
},
divide:function (d1, d2) {
var div = d1 / d2
console.log('Devide: ' + div+'\n');
},
multiplication:function(m1, m2){
var mul = m1 * m2
console.log('Multiplication: ' + mul+'\n');
}
};
module.exports = cal
In this example of calculate module, we have created an object with four functions(i.e. add, minus, divide and multiplication) and assigned this object to module.exports. The module.exports exposes a cal object as a module.
The module.exports is an object and it included, by default, all the js file in the Node js applications.
Now its need to load the created module in our application. There are require() to load the local module in application.
Suppose we have server.js file as a application file.
var myCalModule = require('./calculate.js');// load the module in app
myCalModule.add(11,10);//call load module method from server js
myCalModule.minus(110,10);
myCalModule.divide(100,10);
myCalModule.multiplication(11,10);
In above example the require() revealed the calculate.js module from app root and returns the objects so we can use all the methods of the calculate.js by object like..
myCalModule.minus(110,10);
When we will run server.js by command
nodejs server.js
The output in console looks like..
Add: 21
Minus: 100
Divide: 10
Multiplication: 110
0 Comment(s)