0
0
NodejsConceptBeginner · 3 min read

What Are Modules in Node.js: Simple Explanation and Example

In Node.js, modules are reusable pieces of code that help organize functionality into separate files. Each module can export variables or functions, which other modules can import using require() or import statements to keep code clean and manageable.
⚙️

How It Works

Think of modules in Node.js like different rooms in a house. Each room has a specific purpose and contains things related to that purpose. Similarly, a module is a file that holds code for a specific task or feature.

When you want to use something from another room (module), you open the door (import the module) and take what you need. This keeps your house (project) organized and easy to maintain.

Node.js uses a system called CommonJS for modules, where you use module.exports to share code and require() to bring it in. Newer versions also support ES Modules with export and import syntax.

💻

Example

This example shows a simple module that exports a greeting function, and another file that imports and uses it.

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

module.exports = { sayHello };

// app.js
const greeting = require('./greeting');

console.log(greeting.sayHello('Alice'));
Output
Hello, Alice!
🎯

When to Use

Use modules whenever you want to split your code into smaller, manageable parts. This helps when your project grows bigger or when you want to reuse code in different places.

For example, you can have separate modules for database access, user authentication, or utility functions. This makes your code easier to read, test, and maintain.

Key Points

  • Modules help organize code by splitting it into separate files.
  • Use module.exports and require() in CommonJS modules.
  • ES Modules use export and import syntax.
  • Modules make code reusable and easier to maintain.

Key Takeaways

Modules in Node.js organize code into reusable files.
Use CommonJS with module.exports and require() or ES Modules with export/import.
Modules improve code clarity, reuse, and maintenance.
Split code into modules for different features or tasks.