CommonJS Modules: `require`, `module.exports` in Node.js

beginner
22 min

CommonJS Modules: require, module.exports in Node.js

Welcome 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!

Introduction 🎯

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.

What is 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:

javascript
// main.js const math = require('./mathFunctions'); console.log(math.add(5, 7)); // Output: 12

In 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.

What is 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:

javascript
// 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:

javascript
// main.js const math = require('./mathFunctions'); console.log(math.add(5, 7)); // Output: 12 console.log(math.subtract(10, 5)); // Output: 5

Advanced Example 🎯

Let's create a simple user module that exports a user object with methods for logging in and logging out:

javascript
// 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:

javascript
// 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: false

Quiz 📝

Quick Quiz
Question 1 of 1

What 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! 🤓🚀