🤔 Have you ever noticed this?
Have you ever noticed this?
const express = require("express");
const express2 = require("express");
You called require() twice... but Node.js didn't execute the package twice.
Why? 🤔
Imagine you borrow a book from a library.
The librarian searches the shelf once, hands you the book, and remembers where it is. When someone else asks for the same book, they don't search the entire library again.
Node.js works in a similar way.
The first time you call:
require("./counter");
Node.js:
- 📂 Finds the file
- ⚙️ Executes it
- 📦 Stores the exported object in memory (module cache)
The next time you call:
require("./counter");
It simply returns the cached module instead of executing the file again.
Let's prove it 👇
// counter.js
console.log("Module Loaded");
module.exports = {};
// app.js
require("./counter");
require("./counter");
Output:
Module Loaded
Even though require() is called twice, the module executes only once.
Why does this matter?
Imagine your application has 200 files, and most of them import Express.
Without module caching, Node.js would execute Express hundreds of times.
Instead, it loads Express once and reuses the cached module everywhere, improving performance and reducing unnecessary work.
📌 Key Takeaway
require() doesn't execute a module every time. It executes it once, caches it, and returns the cached version on future calls.
💬 Question for you: Before reading this, did you expect require() to execute the file every time?
Next in Backend Internals:
🔍 What actually happens inside require() before your code even starts running? 👀
Top comments (0)