What Are Modules in Node.js: Simple Explanation and Example
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.
// greeting.js function sayHello(name) { return `Hello, ${name}!`; } module.exports = { sayHello }; // app.js const greeting = require('./greeting'); console.log(greeting.sayHello('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.exportsandrequire()in CommonJS modules. - ES Modules use
exportandimportsyntax. - Modules make code reusable and easier to maintain.