Node JS Tutorial - Modules
In this tutorial, we will learn about modules in Node.js. A module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files that can be reused throughout the Node.js application.
Each module in Node.js has its own context, so it cannot interfere with other modules. Additionally, each module can be placed in a separate .js file under a separate folder.
Creating a Module
Let's create a module. Switch to your project and create a new file named calc.js. Inside this file, create a function expression:
var sum = function(num1,num2){
return num1+num2;
}
Now, export this function through the module.exports object. The module.exports is a special object that is included in every JS file. In a Node.js application, the module is a variable that represents the current module, and exports is an object that will be exposed as a module.
Whatever you assign to module.exports will be exposed as a module. To export the module, write:
module.export = sum
Using a Module
Now, use this module inside the index.js file. Go to the index.js file and require the calc.js file:
var sum = require('./calc');
Now, use the sum function:
console.log(sum(25,50));
Let's run this code. Go to the command prompt and run the command:
node index.js
You will see the sum of the numbers.
Attaching an Object to module.exports
You can also attach an object to module.exports. Let's create a new file named data.js. Inside this file, export an object:
module.export = {
name:"Jenifer",
email:jenifer@gmail.com,
phone:"1234567890"
}
Now, use this object inside the index.js file:
var data = require('./data');
Now, print the data:
console.log(data.name);
console.log(data.email);
cosole.log(data.phone);
Let's run this code. Switch to the command prompt and re-run the command node index.js. You will see the name, email, and phone.
In this way, you can use modules in Node.js.