Nearby lessons
15 of 21📦 Node.js – Module Scope & Module Wrapper Function
📌 What is Module Scope?
What is Module Scope?
In Node.js, each file is treated as a separate module with its own scope. This means that variables declared inside one module are not accessible in another module unless they are explicitly exported.
What is Module Wrapper Function?
Behind the scenes, Node.js does not run our code directly. Instead, it wraps the entire code inside a function before execution. This function is called the Module Wrapper Function. It ensures that variables declared inside a module are scoped to that module only.
⚠️ Case 1: Problem – Name Conflict
Node.js Environment
RUNTIME ACTIVE
require('./module1'); require('./module2');
Terminal Output
✅ Case 2: Solution – Module Scope
Node.js automatically wraps each module's code inside a function.
This provides module scope and prevents variable name conflicts across modules.
🔄 Case 3: Module Wrapper Function in Action
Node.js Environment
RUNTIME ACTIVE
(function () { var myName = "Codings"; console.log(myName); })(); (function () { var myName = "Points"; console.log(myName); })();
Terminal Output
📌 Complete Module Wrapper Syntax
(function (exports, require, module, __filename, __dirname) {
// module code
});
⚡ Use of Module Wrapper Function
- Variables declared with
var,let, orconstare scoped to the module (not global). - Provides global-looking variables like
exports,module,__filename, and__dirname. - Helps in exporting values safely between modules.
🎯 Benefits
- Prevents conflicts between variables across different modules.
- Ensures proper encapsulation.
- Encourages modularity and reusability.
🧠 Test Your Knowledge
4 QuestionsProgress: 0 / 4
Keep Going!Importing JSON Files in Node.js