Skip to main content

Module module

Module module 

Source
Expand description

CommonJS module loader.

Node’s require() semantics, layered on the existing engine — no bespoke VM primitive. A .js file is wrapped in the canonical Node module wrapper (function (exports, require, module, __dirname, __filename) { … }), compiled through the ordinary compile → load_merged path to obtain the wrapper FUNCTION value, then host::invoked with a fresh module = { exports: {} }. Whatever the body assigns to module.exports (or hangs off exports) is the module’s value; it is cached by resolved absolute path so a second require of the same file returns the identical object and circular requires observe the partially-filled exports.

Core modules (fs, path, http, …) short-circuit to their native JsObj::Builtin namespace (see stdlib::resolve) and are never read from disk. Everything else — relative paths, JSON files, and bare node_modules packages with their package.json "exports"/"main" and index.js fallbacks — resolves on the real filesystem and runs the genuine, unmodified source.

Per-module require is a real JS closure that bakes in the defining module’s directory, so a require(...) deferred inside a function called much later still resolves against the module that defined it (a single global “current dir” would resolve against the wrong module). The closure is minted by a one-time compiled factory (FACTORY) invoked with the directory string; it dispatches back into this loader through the __cjs_require / __cjs_resolve global native builtins.

Functions§

cache_delete
Drop key from the module cache, so the next require of that file runs it again. This is what delete require.cache[id] must do to mean anything.
cache_get
The module object cached under the resolved filename key, if any.
cache_keys
The resolved filenames of every currently loaded module, in load order — the keys require.cache exposes.
callsite_stack
An array of depth synthetic V8 CallSite objects for Error.captureStackTrace. Stack-introspection packages (e.g. depd) set Error.prepareStackTrace to a function that receives this array; the getters return neutral placeholders (no real frame info is available), which is enough for those packages to build their deprecation sites without throwing.
entry_dir
The ENTRY script’s base directory.
install_entry_globals
Install the CJS wrapper variables the ENTRY script sees.
require
require(spec) from from_dir: the single entry point shared by the top-level require builtin and the per-module __cjs_require. Returns the module’s exports value.
reset
Clear all per-host loader state. Called from host::reset_host so a fresh eval (which rebuilds the heap) never reuses a stale heap handle.
resolve
Resolve spec relative to from_dir to an absolute file path, or None if no file matches (core modules are handled earlier, by the caller).
set_entry_dir
Set the base directory the ENTRY script’s require resolves against.