Understanding How require() Works in Node.js
Today I deeply understood something that we use daily… but rarely truly understand:
How modules and require() actually work in Node.js.
Let’s break it down in a very simple way.
Step 1: Why Do Modules Even Exist?
Imagine building a big application in a single file.
Variables would clash
Code would become messy
Debugging would be painful
So we divide code into separate files.
Each file = one module.
But here’s the real question:
If I create a variable in one file, should every other file automatically access it?
No.
That would create chaos.
So Node.js protects each file.
Step 2: Modules Work Like Functions
We already know this:
function test() {
let secret = 10;
}
You cannot access secret outside the function.
Why?
Because functions create a private scope.
Node.js uses the exact same idea.
Behind the scenes, every file is wrapped like this:
(function (exports, require, module, __filename, __dirname) {
// your entire file code lives here
});
This wrapper function creates a private scope.
That’s why variables inside a module don’t leak outside.
Step 3: How require() Works Internally
When you write:
const math = require('./math');
Node.js does these steps:
1. Resolve the file path
It finds the correct file.
2. Load the file
Reads the code from disk.
3. Wrap it inside a function
To protect variables.
4. Execute the code
Runs the module once.
5. Store it in cache
So it doesn’t execute again.
6. Return module.exports
Only what you explicitly export is shared.
Why Caching Is Important
Modules are executed only once.
After the first require():
Node stores the result.
Future requires return the cached version.
No reloading, no re-execution.
This improves performance and makes modules behave like singletons.
#NodeJS #JavaScript #BackendDevelopment #WebDevelopment #FullStackDevelopment
Great explanation of Buffers—this kind of core Node.js knowledge really stands out in interviews. 💯