💻 Mastering Modules in Node.js — A Complete Beginner’s Guide

When building apps in Node.js, one of the most fundamental concepts is modules.
But what exactly are modules? And how do require() and module.exports actually work?

Let’s break it down. 👇

💻 What Is a Module?

In Node.js, each JavaScript file is treated as a separate module.
This modular system allows you to split your code into reusable, isolated pieces — making it more maintainable and easier to manage.

// math.js
function add(a, b) {
  return a + b;
}

module.exports = add;
// app.js
const add = require('./math');
console.log(add(2, 3)); // 5

💻 How It Works Behind the Scenes

When you run require('./math'), Node.js does several things:

1 Resolves the path (math.js)
2 Wraps the code inside a function like this:

(function(exports, require, module, __filename, __dirname) {
  // your module code
});

3 Executes the function

4 Returns module.exports

This wrapping is what gives each file access to:

  • require
  • module
  • exports
  • __filename
  • __dirname

💻 module.exports vs exports

Here’s where many beginners get confused.

// ✅ Correct

module.exports = {
  name: 'Samandar',
  greet() {
    console.log('Hello');
  }
};
// ❌ Won’t work as expected
exports = {
  name: 'Samandar'
};
  • exports is just a shortcut to module.exports.
  • If you overwrite exports, you lose the reference to the real module.exports.

So when in doubt — always use module.exports.

💻 Built-in Modules

Node.js also comes with built-in modules like fs, path, http, etc...
No installation required!

const fs = require('fs');
const path = require('path');

💻 Why Modules Matter

  • Code reusability ♻️
  • Cleaner folder structure 📁
  • Easier to test and debug 🧪
  • Foundation for modern frameworks like Express.js

💻 Too Long; Didn't Read

  • Every file in Node.js is a module
  • Use module.exports to share code
  • Use require() to import code
  • Built-in modules come preloaded
  • Don't override exports directly

💬 Whether you're building a CLI tool or a full web app — mastering modules is essential for writing clean, scalable Node.js code. What’s your favorite module trick or tip? Let me know in the comments!