Node.js Modules
Subject: Node.js
Why Use Modules?
- Encapsulation: Keeps code separate and focused on specific tasks.
- Reusability: Allows functions and logic to be reused across files.
- Maintainability: Easier to manage and debug smaller modules.
- Scalability: Supports structured design for larger applications.
Types of Modules in Node.js
- Built-in Modules: Included by default (e.g.,
fs,http,path). - User-defined Modules: Custom files created by developers.
- Third-party Modules: External libraries installed via npm (e.g.,
express,moment).
1. Built-in Modules
Node.js includes a set of core modules you can import directly.
Explanation:
require("fs")imports Node’s file system module.
2. User-defined Modules
Create and export functions from custom files.
Step 1: Create Module (math.js)
Step 2: Use the Module (app.js)
Explanation:
module.exportsexposes the functions.require("./math")imports the module.
3. Third-party Modules
Install using npm and require in your code.
Step 1: Install
Step 2: Use
Explanation:
- Useful for working with dates, strings, utilities, etc.
- Modules are placed inside
node_modules/folder.
Module Caching in Node.js
Once a module is loaded, it is cached. This avoids reloading it on every require() call, improving performance.
Directory Structure Example
exports vs module.exports
exportsis a shortcut tomodule.exports.- Don’t assign a new object to
exports; modifymodule.exportsdirectly.
Correct:
Incorrect:
Best Practices
- Keep each module focused on one responsibility.
- Use consistent file naming.
- Avoid circular dependencies.
- Separate logic into config, utils, routes, etc.
Key Takeaways
- Node.js modules improve organization and maintainability.
- Use
require()to import andmodule.exportsto expose code. - Built-in, custom, and third-party modules support modular development.
- Third-party libraries enhance functionality and reduce development time.
- Caching and proper design patterns make modules efficient and scalable.