Skip to the solution
EasyPhone Screen4 min read

Explain how modules work in Node.js.

826 views

The problem

Question presented to candidate: "You call require('./db') from three different files in the same process. Do you get three separate module instances, or one shared instance β€” and how would you actually prove which one happens?"

What a strong answer should cover:

  • Every CommonJS file is wrapped by Node in an implicit function before execution, receiving five parameters: exports, require, module, __filename, __dirname β€” this is why those identifiers are available inside any .js file without an explicit import.
  • πŸ“Œ The module cache is the key mechanism: require() resolves a specifier to an absolute file path, and if that exact path has already been loaded once in this process, require() returns the cached module.exports object instead of re-running the file β€” verifiably the SAME object reference (===), not just an equal-looking copy.
  • This means a module's top-level state (a counter, a cached connection, a singleton) is naturally shared across every file that require()s it in the same process β€” this is both the mechanism behind the common "singleton via module" pattern, and a source of surprising bugs when that sharing is unintended.
  • module.exports (the object actually returned by require()) and the bare exports variable start out pointing at the same object, but reassigning exports = {...} breaks that link β€” only reassigning module.exports itself changes what require() actually returns. This is a common, verifiable source of "why did my export not show up" bugs.
  • Node resolves a bare specifier like require("./db") by trying, in order, an exact file match, then common extensions (.js, .json, .node), then a directory with an index.js or a "main" field β€” a good answer names this resolution order rather than treating it as unspecified magic.
  • The module cache is keyed by the resolved absolute path β€” two different relative specifiers that resolve to the same file (e.g. from two different directories) still hit the same cache entry, and the module still executes only once.

Clarifying questions expected:

  • "Is the concern about state sharing being a bug, or intentionally relying on the singleton pattern?" β€” the caching behavior is the same either way; the framing of "is this a problem" differs.
  • "CommonJS specifically, or does the codebase also use ES Modules?" β€” the caching mechanism and its guarantees differ subtly between the two systems, covered in the dedicated CommonJS-vs-ESM question.

Code / implementation expected: Yes β€” actually requiring the same file twice and showing the returned objects are identical and share mutated state is the concrete, convincing proof here.

  • modules
  • commonjs
  • es modules
  • imports

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read Β· 8 sections

Read the code

JavaScriptrequire() caches by resolved path β€” same object, shared state, module body runs only once
// module-a.js
let counter = 0;
module.exports = { increment() { return ++counter; } };
console.log("module-a.js body executed");

// main.js
const a1 = require("./module-a.js");
const a2 = require("./module-a.js");
console.log("same instance?", a1 === a2);
console.log(a1.increment());
console.log(a2.increment());

// Output:
// module-a.js body executed   <- only ONCE
// same instance? true
// 1
// 2                            <- shared state, not a fresh copy

// The module wrapper's five implicit parameters, confirmed:
// [ 'object', 'function', 'object', 'string', 'string' ]
//   exports    require    module    __filename  __dirname

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 10 of 152 in Node.js

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Node.js questions
Up nextEasy

What are the main security risks of using the 'eval()' function in Node.js?

Continue