require, module.exports in Node.jsWelcome to our comprehensive guide on CommonJS Modules in Node.js! We'll walk you through the essential concepts of require and module.exports, two powerful tools for organizing and managing your Node.js projects. Let's dive in!
Organizing your code becomes crucial as projects grow in size and complexity. This is where CommonJS Modules come in! They help break down larger projects into smaller, manageable pieces, making it easier to maintain and reuse code.
In Node.js, every file is a module, and we can use require and module.exports to interact with these modules.
require? 📝The require function is used to import or load other modules. It searches for a module based on the file name with the extension .js. Here's a simple example:
// main.js
const math = require('./mathFunctions');
console.log(math.add(5, 7)); // Output: 12In the above example, we have a mathFunctions.js file that exports some mathematical functions, and we're importing it into our main.js file using require.
module.exports? 📝module.exports is an object that we use to export functions, objects, or values from our module. When a module is loaded, Node.js assigns the value of module.exports to the module object.
Let's modify our mathFunctions.js file:
// mathFunctions.js
module.exports = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};Now, when we import mathFunctions in our main.js, we can access the add and subtract functions:
// main.js
const math = require('./mathFunctions');
console.log(math.add(5, 7)); // Output: 12
console.log(math.subtract(10, 5)); // Output: 5Let's create a simple user module that exports a user object with methods for logging in and logging out:
// user.js
const users = {
alice: { username: 'alice', password: '123' },
bob: { username: 'bob', password: '456' }
};
module.exports = {
login: function(username, password) {
return users[username] && users[username].password === password;
},
logout: function(username) {
delete users[username];
}
};Now, we can use this user module in our app.js:
// app.js
const user = require('./user');
console.log(user.login('alice', '123')); // Output: true
console.log(user.login('charlie', '123')); // Output: false
user.logout('alice');
console.log(user.login('alice', '123')); // Output: falseWhat is the purpose of the `require` function in Node.js?
We hope you found this tutorial helpful! With a solid understanding of require and module.exports, you're well on your way to building scalable and maintainable Node.js projects. Happy coding! 🤓🚀