The module is a plain JavaScript Object representing the current module. It is local to each module and also it is private. It has exports property which is a plain JavaScript variable, set to module.exports. At the end of the file, Node.js return module.exports to the required function.
About module.exports:
When we want to export a single class/variable/function from one module to another module, we use module.exports.
Example: Create two files calculator.js and operation.js and export the Arithmetic class from calculator.js to operation.js using module.exports method. Here, we have created a class Arithmetic and exported the whole class using module.exports.
Filename: calculator.js
class Arithmetic { constructor(a, b) {
this .a = a;
this .b = b;
}
add() {
return this .a + this .b;
}
subtract() {
return this .a - this .b;
}
multiply() {
return this .a * this .b;
}
divide() {
if ( this .b != 0) {
return this .a / this .b;
}
return "divided by zero !!!!" ;
}
}; module.exports = Arithmetic; |
Filename: operation.js
const Arithmetic = require( './calculator.js' );
const op = new Arithmetic(100,40);
console.log(`Addition -> ${op.add()}`); console.log(`subtraction -> ${op.subtract()}`); console.log(`Multiplication -> ${op.multiply()}`); console.log(`Division -> ${op.divide()}`); |
Run the operation.js file using the following command:
node operation.js
Output:
About exports:
When we want to export multiple variables/functions from one module to another, we use exports.
Example: Create two files calculator.js and operation.js and export multiple functions from calculator.js file.
Filename: calculator.js
exports.add = (a, b) => a + b; exports.subtract = (a, b) => a - b; exports.multiply = (a, b) => a * b; exports.divide = (a, b) => { if (b != 0) {
return a / b;
}
return `Divided by zero !!!`;
} |
Filename: operation.js
const Arithmetic = require( './calculator.js' );
console.log(`Addition -> ${Arithmetic.add(100,40)}`); console.log(`subtraction -> ${Arithmetic.subtract(100,40)}`); console.log(`Multiplication -> ${Arithmetic.multiply(100,40)}`); console.log(`Division -> ${Arithmetic.divide(100,40)}`); |
Run the operation.js file using the following command:
node operation.js
Output:
Key differences between module.exports and exports:
S.no |
Module.exports |
Exports |
---|---|---|
1 |
When we want to export a single class/variable/function from one module to another module, we use the module.exports way. | When we want to export multiple variables/functions from one module to another, we use exports way. |
2. |
It is the object reference that gets returned from the require() calls. | exports is not returned by require(). It is just a reference to module.exports. |