Function scope = module scope
The same JS rule, renamed.
- Variables declared inside a function are unreachable from outside.
- Node applies the same rule: each
.jsfile is wrapped in a function before V8 sees it. - That’s why module variables can’t collide across files.
- The only way data leaves a module is through explicit
module.exports.
IIFE — the pattern behind it
Create and immediately invoke.
(function() { ... })()— declared + executed in one shot.- The outer
()turns the declaration into an expression. - The trailing
()runs it immediately. - Great for isolating state without polluting any scope — exactly what a module needs.
Module Wrapper & its 5 params
What Node actually wraps your file with.
(function (exports, require, module, __filename, __dirname) { YOUR_CODE }).exports— shorthand pointer tomodule.exports.require— the import function (it’s a parameter, not a global).module— the current module object;module.exportsis its return value.__filename/__dirname— absolute path of the file and its folder.
require() in 5 steps
The interview question — drilled.
- Resolve — figure out the absolute path (local file / core / npm / json).
- Load — read the source from disk into memory (not executed yet).
- Wrap — inject into the Module Wrapper Function.
- Evaluate — V8 executes;
module.exportsis populated and returned. - Cache — store the module; subsequent
requirecalls return the cached object.
V8 + libuv — the two pillars
Where JS ends and the OS begins.
- V8 (C++): runs JS, manages call stack + memory heap, runs the garbage collector.
- libuv (C): event loop, thread pool, talks to the OS for file I/O, networking, timers.
- Core modules (
fs,http,path) are JS files underlib/in the Node repo. requireitself is built bymakeRequireFunctioninlib/internal/modules/helpers.js.
Comments
Comments are disabled in this environment. Set
PUBLIC_GISCUS_REPO,PUBLIC_GISCUS_REPO_ID, andPUBLIC_GISCUS_CATEGORY_IDto enable.