Course contentsShow
← JavaScript
Lesson 1447 of 2,72331. ModulesFree lesson

The Module Wrapper Function

See how Node wraps each file in a function providing require, module, exports, __filename, __dirname.

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 to module.exports
  • require: The function you use to import other modules
  • module: 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.