6. Node.js Modules – Creating & Exporting Your Own Modules

As your application grows, writing all code in a single file becomes difficult to manage. Node.js modules help us split code into multiple files and reuse them easily.

Node.js modules concept

Splitting code into reusable modules in Node.js

1. What is a Module?

A module is a separate file that contains specific functionality. We can export it and use it in another file.

  • Clean
  • Reusable
  • Maintainable

2. Creating Your First Module

Create a file named math.js

function add(a, b) {
  return a + b;
}

module.exports = add;

3. Importing the Module

Create another file app.js

const add = require("./math");

console.log(add(5, 3));

Output:

8

4. Exporting Multiple Values

function add(a, b) {
  return a + b;
}

function sub(a, b) {
  return a - b;
}

module.exports = { add, sub };

Importing:

const math = require("./math");

console.log(math.add(10, 5));

5. exports vs module.exports

  • module.exports → Export values
  • exports → Shortcut

6. Types of Modules

  • Local Modules
  • Core Modules (fs, http, path)
  • Third-party Modules

7. Real-World Usage

  • Database connections
  • Authentication logic
  • Utility functions
  • API services

8. Common Beginner Mistakes

  • Missing ./ in path
  • Wrong file name
  • Not exporting
Without modules, large applications become difficult to manage.

Conclusion

Now you are writing modular and professional Node.js code.

Your Hero to Zero Node.js journey is becoming production-ready ⚡🚀

Chakrapani U

Hi, I’m Chakrapani Upadhyaya, an IT professional with 15+ years of industry experience. Over the years, I have worked on web development, enterprise applications, database systems, and cloud-based solutions. Through this blog, I aim to simplify complex technical concepts and help learners grow from beginners to confident, industry-ready developers.

Previous Post Next Post

نموذج الاتصال