0
0
NodejsConceptBeginner · 3 min read

What is module.exports in Node.js: Simple Explanation and Usage

module.exports in Node.js is an object that defines what a module shares with other files when it is imported. It lets you specify functions, objects, or values that other files can use by requiring the module.
⚙️

How It Works

Think of each Node.js file as a small box that holds some tools or information. module.exports is like the label on the box that tells others what they can take out and use. When another file wants to use something from this box, it looks at the label to see what is available.

By default, each file has its own module.exports object. You can put anything you want on this object—like functions, numbers, or objects—and that becomes what other files get when they import your module. This system helps keep code organized and reusable, just like sharing tools in a workshop.

💻

Example

This example shows how to export a function from one file and use it in another.

javascript
// file: greet.js
function sayHello(name) {
  return `Hello, ${name}!`;
}

module.exports = sayHello;

// file: app.js
const greet = require('./greet');
console.log(greet('Alice'));
Output
Hello, Alice!
🎯

When to Use

Use module.exports whenever you want to share code between files in a Node.js project. For example, you can export utility functions, configuration settings, or classes from one file and import them in others. This helps keep your code clean and modular, making it easier to maintain and reuse.

It is especially useful in larger projects where splitting code into smaller parts improves organization and collaboration.

Key Points

  • module.exports defines what a module shares with others.
  • It can export any JavaScript value: functions, objects, strings, etc.
  • Other files use require() to import what module.exports provides.
  • Helps keep code modular and reusable across files.

Key Takeaways

module.exports controls what a Node.js module shares with other files.
You can export functions, objects, or any value using module.exports.
Other files import these exports using require().
Using module.exports helps organize code into reusable parts.