In NodeJS, a module is a block of code that encapsulates(groups) related functionality, making it reusable and easier to manage. Modules help organize code into seperate files(modules) and allows us to export(expose functionality to other files) and import(use) functionality between files.
So in NodeJS every .js file is considered to be a seperate module.
📦 Type of Modules:
There are 3 types of Module in NodeJS
1. Built in Modules
fs
, http
2. User Defined Modules
3. Third Party Modules
express
, lodash
1 Example User Defined Module
Following below code should be placed inside a app.js file. In this code we have imported(used the functionality of math (user defined module). To import the functionality of math module we have used the require() function. The name of the module is passed as string. The name of module begins with "./" which indicates that the methods are defined in the current user working directory.
const math = require('./math');
let a = 10;
let b= 13;
console.log(`The Sum of a and b is = ${math.add(a,b)}`);
console.log(`The Difference of a and b is = ${math.subtract(a,b)}`)
console.log(`The Product of a and b is = ${math.multiply(a,b)}`)
console.log(`The Division of a over b is = ${math.divide(a,b)}`)
The following code should be placed in the math.js file. this math.js file is a module because we have placed all the maths related functions inside separate file. to export the functions of this file we have used the module.exports = {}. It means that we are exporting exports an object containing the functions add, subtract, multiply, and divide.
Note that the module.exports should be used once in the program as it will overwrite the previous exports.
function add(a, b){
return a+b;
}
function subtract(a,b){
return a-b;
}
function multiply(a,b){
return a*b;
}
function divide(a, b){
return a/b;
}
module.exports = {add, subtract, multiply, divide};
Another way is to use the exports.method_name. We can use this exports.method_name to export multiple function from same file. just there is the difference of syntax
exports.add = function (a, b){
return a+b;
}
exports.subtract = function (a, b){
return a-b;
}
exports.multiply = function (a, b){
return a*b;
}
exports.divide = function (a, b){
return a/b;
}
2 Example Built in Module
To use the Built in module we use the same require() function and pass the name of module as we did in User Defined Module Example. But the name of module does not begin with './' if you add './' then we will get error that module was not found.
const fs = require('fs');
fs.appendFileSync('log.txt', "Hi I am File System");
console.log('File has been Created using the built in FS Module');
0 Comments