In Node.js and CommonJS (CJS) modules, require(id) is a synchronous function injected into each module’s wrapper scope that resolves id to a concrete file or built-in/package path (Module._resolveFilename), checks the module cache (require.cache), loads and compiles the module if uncached (wrapping its code in a function (exports, require, module, __filename, __dirname) so top-level declarations stay module-scoped), populates module.exports, caches the module object, and returns module.exports—always guard dynamic module lookups with typeof / instanceof checks, a Map for tracked module entries, and try / catch blocks so missing or cyclic modules fail cleanly.


1. How require() Resolves, Wraps, Caches, and Returns module.exports

Each CommonJS module executes inside a module wrapper function with its own require, module, exports, __filename, and __dirname, returning module.exports (not a direct reference to exports if module.exports = ... is reassigned):

// CommonJS module loader wrapper with validation, Map cache inspection, and try/catch
function safeRequireModule(moduleId, requireFn = (typeof require === "function" ? require : null), loadedMap = new Map()) {
  if (typeof moduleId !== "string" || moduleId.trim().length === 0) {
    throw new TypeError("Expected moduleId to be a non-empty string.");
  }
  if (typeof requireFn !== "function") {
    throw new TypeError("Expected requireFn to be a valid CommonJS require function.");
  }
  if (!(loadedMap instanceof Map)) {
    throw new TypeError("Expected loadedMap to be a Map instance.");
  }

  try {
    const cleanId = moduleId.trim();
    const resolvedPath = typeof requireFn.resolve === "function"
      ? requireFn.resolve(cleanId)
      : cleanId;

    if (loadedMap.has(resolvedPath)) {
      return loadedMap.get(resolvedPath);
    }

    const exportedValue = requireFn(cleanId);
    loadedMap.set(resolvedPath, exportedValue);
    return exportedValue;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed loading CommonJS module "${moduleId}": ${message}`);
  }
}

// Example usage:
// try {
//   const trackedModules = new Map();
//   const urlModule = safeRequireModule("node:url", require, trackedModules);
//   console.log("URL module loaded:", typeof urlModule.URL);
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Resolution order: Built-in/core modules (node:fs, path) -> relative/absolute files (.js, .json, .node, or index.js inside a directory) -> node_modules lookup walking up parent directories.
  • Caching by resolved filename: Subsequent require() calls for the same resolved path return the cached module.exports object immediately without re-executing the file body.

2. Inspecting Module Cache Entries and Exports with a Map

When auditing loaded CommonJS modules or inspecting require.cache entries safely without mutating internal loader state blindly, index metadata in a Map:

// Inspect cached CommonJS module filenames and export types into a Map
function inspectRequireCacheToMap(cacheObject = (typeof require !== "undefined" ? require.cache : null)) {
  if (cacheObject === null || typeof cacheObject !== "object") {
    throw new TypeError("Expected cacheObject to be a valid require.cache object.");
  }

  try {
    const cacheSummaryMap = new Map();

    for (const [filename, modEntry] of Object.entries(cacheObject)) {
      if (typeof filename !== "string" || !modEntry || typeof modEntry !== "object") {
        continue;
      }

      const exportsRef = modEntry.exports;
      const exportType = exportsRef === null ? "null" : typeof exportsRef;

      cacheSummaryMap.set(filename, {
        id: typeof modEntry.id === "string" ? modEntry.id : filename,
        loaded: Boolean(modEntry.loaded),
        exportType
      });
    }

    return cacheSummaryMap;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed inspecting require.cache: ${message}`);
  }
}

// Example usage:
// try {
//   const summaryMap = inspectRequireCacheToMap();
//   console.log("Cached modules count:", summaryMap.size);
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Use Map rather than a plain object for module path keys: File paths can contain special characters or match Object.prototype names.
  • require() is synchronous: It blocks execution until the target module finishes evaluating, making it unsuitable for lazy network-style loading without async wrappers or dynamic import().

3. Circular Dependencies, module.exports vs. exports, and ESM Caveats

Keep these CommonJS and Node.js module behaviors in mind in production code:

  • Circular require() calls return partially evaluated module.exports: When module A requires B and B requires A, B receives whatever A.exports has assigned up to that line before A finishes executing.
  • Reassigning exports = ... breaks the alias to module.exports: Inside the wrapper, exports starts equal to module.exports; assigning exports = fn only rebinds the local parameter unless you assign module.exports = fn.
  • ESM (import) vs. CommonJS (require()): In ESM contexts ("type": "module" or .mjs), global require is not defined by default (create one via createRequire(import.meta.url) if CJS interop is required), and CJS modules imported into ESM expose their exports under .default or named bindings depending on Node’s interop rules.