Search lands in PR-5.1 (Pagefind).

Explanation Intermediate

Chapter 5 Updated

Module Internals — IIFE, Wrapper & require()

The module wrapper function, the 5 injected parameters, and the 5 steps of require() — interview gold.

  • Full 16m
  • Revision 4m
  • Flow 2m

Function scope = module scope

The same JS rule, renamed.

  • Variables declared inside a function are unreachable from outside.
  • Node applies the same rule: each .js file 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 to module.exports.
  • require — the import function (it’s a parameter, not a global).
  • module — the current module object; module.exports is 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.exports is populated and returned.
  • Cache — store the module; subsequent require calls 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 under lib/ in the Node repo.
  • require itself is built by makeRequireFunction in lib/internal/modules/helpers.js.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.