DEV Community

Cover image for Modules in Node.js
Samandar Hodiev
Samandar Hodiev

Posted on

Modules in Node.js

๐Ÿ’ป 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;
Enter fullscreen mode Exit fullscreen mode
// app.js
const add = require('./math');
console.log(add(2, 3)); // 5
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ป 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
});
Enter fullscreen mode Exit fullscreen mode

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');
  }
};
Enter fullscreen mode Exit fullscreen mode
// โŒ Wonโ€™t work as expected
exports = {
  name: 'Samandar'
};
Enter fullscreen mode Exit fullscreen mode
  • 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');
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ป 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!

Top comments (0)