Module Examples
A module in Node.js is a self-contained unit of code that exports functions or objects for other code to consume. It helps in organizing and reusing code, and in encapsulating implementation details.
Here's an example of a simple Node.js module that exports a function to calculate the sum of two numbers:
// myModule.js
exports.sum = function(a, b) {
return a + b;
};
And here's how to use the module in another file:
// app.js
var myModule = require('./myModule');
var result = myModule.sum(1, 2);
console.log(result); // Outputs: 3
Here's an example of a simple Node.js module that exports a function that returns a Promise:
// myModule.js
exports.asyncSum = function(a, b) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (a > b) {
resolve(`${a} is greater than ${b}`);
} else {
reject(`${a} is less than ${b}`);
}
}, 1000);
});
};
And here's how to use the module and handle the returned Promise in another file:
// app.js
var myModule = require('./myModule');
myModule.asyncSum(3, 2)
.then(result => {
console.log(result); // Outputs: 3 is greater than 2
})
.catch(error => {
console.error(error);
});