DEV Community

Cover image for Node.js Internals #1: Why require() Doesn't Run Your File Again
Krati Joshi
Krati Joshi

Posted on

Node.js Internals #1: Why require() Doesn't Run Your File Again

🤔 Have you ever noticed this?

Have you ever noticed this?

const express = require("express");
const express2 = require("express");
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

Node.js:

  • 📂 Finds the file
  • ⚙️ Executes it
  • 📦 Stores the exported object in memory (module cache)

The next time you call:

require("./counter");
Enter fullscreen mode Exit fullscreen mode

It simply returns the cached module instead of executing the file again.

Let's prove it 👇

// counter.js
console.log("Module Loaded");

module.exports = {};
Enter fullscreen mode Exit fullscreen mode
// app.js
require("./counter");
require("./counter");
Enter fullscreen mode Exit fullscreen mode

Output:

Module Loaded
Enter fullscreen mode Exit fullscreen mode

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)