The Module Wrapper Function
You'll learn how Node.js secretly wraps your code in a function before executing it.
When you write a CommonJS module in Node.js, you might think your code runs exactly as written. In reality, Node.js wraps every module file in a special function before execution. This wrapper function is why features like require, module, exports, __filename, and __dirname are available in your code without you explicitly declaring them.
The Invisible Wrapper
Here's what actually happens behind the scenes. When you write this:
// myModule.js
const data = 'Hello';
module.exports = data;
Node.js wraps it like this before executing:
(function(exports, require, module, __filename, __dirname) {
// Your code goes here
const data = 'Hello';
module.exports = data;
});
What This Provides
The wrapper function passes five parameters to your code:
exports: A shorthand reference tomodule.exportsrequire: The function you use to import other modulesmodule: An object representing the current module__filename: The absolute path to the current file__dirname: The absolute path to the current directory
This is why you can use these without importing them—they're function parameters!
Why This Matters
The wrapper creates module scope instead of global scope. Variables you declare stay private to your module unless explicitly exported. Without this wrapper, everything would pollute the global namespace, causing conflicts between modules.
Key Takeaway: Node.js wraps every CommonJS module in a function that provides require, module, exports, __filename, and __dirname as parameters, creating isolated module scope and enabling the module system to work.