Skip to solution
easyPhone Screen

Explain how modules work in Node.js.

825 views
01

Understand 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.

modulescommonjses modulesimports
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Target Audience: Engineers preparing for Node.js phone screens — assumes very basic JavaScript familiarity, no prior module-system knowledge required. Difficulty: Easy

How to read this doc: Concepts are explained in plain language first, then tagged with 📌 Interview term:. The caching behav

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

require() 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
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 10 of 152 decoded in the Node.js track. One more won't hurt.

Back to track