1. What Are Modules?
- Modules are individual blocks of reusable code in Node.js.
- Each file in Node.js is treated as a module, encapsulating code and making it reusable in other parts of the application.
- Helps in organizing code and promoting reusability.
2. Types of Modules
Node.js modules come in different forms:
- Core Modules: Built-in modules that come with Node.js, like
fs,http,path,events, etc. - Local/User-Defined Modules: Custom modules created by the developer in the project.
- Third-Party Modules: Modules installed from npm (Node Package Manager), like
express,mongoose,lodash, etc.
3. Core Modules
- These are part of the Node.js runtime environment, and you can use them without installing anything.
- Example:
const fs = require('fs'); // 'fs' is a core module for file system operations.4. Local/User-Defined Modules
- Any JavaScript file you create can be a module.
- You can export functions, objects, or variables from one file and import them into another using
module.exportsandrequire. Example:
- Exporting from a module (math.js):
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };- Importing in another file (app.js):
const math = require('./math');
console.log(math.add(5, 10)); // Output: 155. Third-Party Modules (npm)
- These are modules you install using npm (Node Package Manager).
- Example:
npm install lodash6. How to Export from a Module
Node.js provides a couple of ways to export code from a module:
module.exports: This allows you to export functions, objects, classes, etc. For example:
// math.js
module.exports.add = function (a, b) {
return a + b;
};exports: A shorthand formodule.exports. However, assigning a value directly toexportscan break its reference tomodule.exports.
Example of shorthand:
// math.js
exports.add = function (a, b) {
return a + b;
};- Important Note: If you assign something directly to
exports, likeexports = {}orexports = someFunction, it will no longer point tomodule.exports.
7. How to Import a Module
- require(): Use
require()to import a module.- It can import core, local, and third-party modules.
- Example:
const math = require('./math');
const fs = require('fs'); // core module
const _ = require('lodash'); // npm module8. Module Caching
- Node.js caches modules after they are loaded for the first time.
- If you
requirethe same module multiple times, Node.js will return the cached version instead of reloading it. - This enhances performance, but you can bypass this by clearing the cache or forcing the module to reload.
9. ES6 Modules (ESM) in Node.js
- Starting with Node.js 12+, ECMAScript Modules (ESM) are supported with
.mjsfiles or by using the"type": "module"field in thepackage.json. - ESM uses
importandexportsyntax, which is different from CommonJS (require()andmodule.exports).
10. Resolving Modules
- Node.js resolves modules in the following order:
- Core Modules (e.g.,
http,fs, etc.) - Relative Path Modules (e.g.,
./math) - Node Modules (from
node_modulesfolder) - Absolute Paths (if using custom path configurations)
- Core Modules (e.g.,
- If no module is found, Node.js throws a
MODULE_NOT_FOUNDerror.
11. Node Package Manager (npm)
- npm is the default package manager for Node.js, which allows developers to install, share, and manage third-party modules.
- Commands:
npm install <package>: Installs a package.npm uninstall <package>: Removes a package.npm update: Updates packages.npm init: Initializes a new Node.js project and generates apackage.json.
12. package.json
package.jsonis a manifest file in every Node.js project.- It holds metadata about the project and lists dependencies (modules required for the project).
13. Transpiling with Babel (for using ES6 in older Node.js versions)
- Node.js has partial support for ES6 modules. For full ES6+ feature support, developers use Babel to transpile ES6 code into ES5 (CommonJS) so it can run in Node.js.
14. Common Errors
- MODULE_NOT_FOUND: Module couldn’t be found, often due to incorrect path or missing module installation.
- Cannot use import/export outside a module: Happens if you try to use ES6
import/exportin a CommonJS context without proper configuration (like"type": "module"inpackage.json).