Hey awesome devs! π Have you ever wondered how to share functions, objects, or variables across different files in Node.js? Thatβs where module exports come in! In this blog, weβll break it down step by step so you can master module exports and make your Node.js code clean, organized, and reusable! π‘
π§ What is module.exports
?
In Node.js, every file is a module by default. If you want to share something from one file to another, you need to export it. The module.exports
object is what allows us to do that!
Think of it as a backpack π where you pack functions, objects, or variables so other files can use them.
π Basic Example of module.exports
Letβs create a simple module that exports a function.
π Step 1: Create greet.js
// greet.js
function sayHello(name) {
return `Hello, ${name}!`;
}
// Export the function
module.exports = sayHello;
Here, we created a function sayHello
and exported it using module.exports
.
π Step 2: Import and Use the Module
Now, letβs use the greet.js
module inside app.js
.
// app.js
const sayHello = require('./greet');
console.log(sayHello('Sovannaro')); // Output: Hello, Sovannaro!
Run the file with:
node app.js
Boom! π You just used module.exports
to share a function across files!
π₯ Exporting Multiple Functions or Variables
If you want to export multiple things, you can use an object.
π Step 1: Update math.js
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
// Export multiple functions
module.exports = {
add,
subtract
};
π Step 2: Import and Use the Module
// app.js
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8
console.log(math.subtract(10, 4)); // Output: 6
π― Alternative: exports
vs module.exports
You might see exports
being used instead of module.exports
. Hereβs the difference:
β
Using module.exports
module.exports = function() {
console.log("Hello from module.exports");
};
β
Using exports
(Shortcut)
exports.sayHi = function() {
console.log("Hello from exports");
};
β οΈ Warning: Donβt assign a new value directly to exports
, or it wonβt work!
β Incorrect usage:
exports = function() {
console.log("This wonβt work!");
};
π Final Thoughts
module.exports
is a powerful feature that helps you organize your Node.js applications. Whether youβre exporting a single function or multiple objects, understanding how to use it will make your code modular, reusable, and easier to maintain. πͺ
This is just the beginning! In the next article, weβll dive deeper into Module Scopeβstay tuned! π―
If you found this blog helpful, make sure to follow me on GitHub π github.com/sovannaro and drop a β. Your support keeps me motivated to create more awesome content! π
Happy coding! π»π₯
Top comments (0)