All academies

Simulator

Module System Simulator

How does require() actually work — and what does ESM do differently? Step through the loading pipeline, watch the module cache fill up, and compare the two systems.

app.js
const math = require('./math');
const logger = require('./logger');

logger.log('2 + 3 = ' + math.add(2, 3));
math.js
function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

module.exports = { add, multiply };
logger.js
exports.log = (msg) => {
  const time = new Date().toISOString();
  console.log(`[${time}] ${msg}`);
};

What require() does

1 · Resolve
2 · Load
3 · Wrap
4 · Execute
5 · Cache
6 · Return

Press a run button to step through the pipeline. Run the same module twice to see the cache short-circuit it.

require.cache

Empty — no modules loaded yet.

Modules are singletons: every require()of the same file returns the same exports object. That's why a database connection created in a module is shared across your whole app.