DEV Community

Cover image for 🚀 Backend Internals #3: Your Node.js File Isn't Executed Directly—Here's Why
Krati Joshi
Krati Joshi

Posted on

🚀 Backend Internals #3: Your Node.js File Isn't Executed Directly—Here's Why

Have you ever wondered how require, module, exports, __dirname, and __filename are available in every Node.js file without importing them?

It feels like magic...

But there's a hidden trick behind the scenes. 🪄


📦 Imagine This...

Think of submitting an assignment to your teacher.

Before it's checked, the teacher places it inside a folder that already contains:

  • 📝 Your name
  • 📚 Subject
  • 🆔 Roll number
  • 📂 Extra instructions

Your assignment isn't processed alone—it gets wrapped with useful information first.

Node.js does something very similar.


⚙️ The Hidden Wrapper

Before executing your code, Node.js wraps every CommonJS module inside a hidden function like this:

(function (exports, require, module, __filename, __dirname) {
  // Your code goes here
});
Enter fullscreen mode Exit fullscreen mode

That's why these variables are available automatically—you never had to create or import them.


💡 What Does Each One Do?

  • 📥 require → Imports another module.
  • 📤 exports → Exports values from the current module.
  • 📦 module → Represents the current module.
  • 📄 __filename → Full path of the current file.
  • 📁 __dirname → Directory of the current file.

🧪 Let's Prove It

console.log(__filename);
console.log(__dirname);
Enter fullscreen mode Exit fullscreen mode

Even though you never declared these variables, Node.js provides them through the module wrapper.


🚀 Why Does Node.js Use a Wrapper?

The wrapper helps Node.js:

  • 🔒 Keep variables scoped to the current module.
  • 📦 Inject useful variables automatically.
  • 🛡️ Prevent pollution of the global scope.
  • ⚙️ Manage modules efficiently.

Without this wrapper, every file would share the same global scope, making applications harder to maintain.


🎤 Interview Question

Q: Why can we use __dirname without importing it?

Answer: Because Node.js injects it into every CommonJS module using the hidden module wrapper function.


🧩 Quick Challenge

Without running the code, what do you think this prints?

console.log(typeof require);
console.log(typeof module);
console.log(typeof exports);
Enter fullscreen mode Exit fullscreen mode

🤔 Drop your answer in the comments before testing it!


📌 Key Takeaway

Your Node.js file isn't executed directly.

Before running your code, Node.js wraps it inside a hidden function and provides useful variables like require, module, exports, __filename, and __dirname.

Once you understand the wrapper, many "magical" Node.js features suddenly make perfect sense.


💬 Question for you: Which one have you used the most—__dirname, require, or module.exports?


🚀 Next in Backend Internals

exports vs module.exports — What's the Difference and When Should You Use Each?

Top comments (0)