Node JS Tutorial - Module Patterns

In this tutorial, we will learn about Module Patterns and explore different ways to use modules.

Creating Multiple Functions in a Module

Let's go to the project and inside the calc.js file, create some more functions. First, create a function to subtract two numbers:


var sub = function(num1,num2){
return num1-num2;
}

Next, create another function to multiply two numbers:


var multiply = function(num1*num2){
return num1*num2;
}

Now, export these functions:


module.exports.sum = sum;
module.exports.sub=sub;
module.exports.multiply=multiply;

Using the Module in index.js

Now, let's use these methods in the index.js file. First, require the calc.js file:


var calc=require('./calc');

Next, use these functions:


console.log(calc.sum(20,40));
console.log(calc.sub(40,20));
console.log(calc.multiply(20,40));

Let's run this code. Go to the command prompt and run the command:


node index.js

Now, you can see all the results on the console.

Alternative Way to Export a Module

You can also export a module in a different way. Go to the calc.js file and export the module as follows:


module.exports={
Sum:sum,
Sub:sub,
Multipy:multiply
}

Let's check if it's working. Just re-run the index.js file, and you can see that it's working as before.

In this way, you can use modules in different ways, providing flexibility in your Node.js applications.