QA
Intermediate LevelNode JS

How does the Node.js module resolution algorithm locate packages inside nested node_modules folders?

❓ Interview Prompt: When requiring "pkg", Node checks ./node_modules/pkg. If missing, it traverses up parent directories (../node_modules) all the way to root /node_modules, then checks global NODE_PATH and package.json exports.

When resolving a module reference (e.g. 'require('lodash')'), Node.js uses a recursive lookup algorithm:

1
Checks for built-in modules ('node:fs').
2
Looks in current directory './node_modules/lodash'.
3
Traverses up parent directories ('../node_modules/lodash', '../../node_modules/lodash') up to system root '/node_modules'.
4
Checks 'package.json' 'exports' field for module entry point mapping.

Code Implementation Example

javascript
console.log('Module resolution paths:', module.paths);
💡Inspecting Node.js module resolution lookup directory paths.
🎯 Interview Key Takeaway

Understand node_modules resolution traversal to debug dependency resolution and hoisting issues.

#module resolution#node_modules#npm#Intermediate
Back to all Node JS Questions→

More Node JS Interview Questions

Beginner LevelNode JS

How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).

Beginner LevelNode JS

What does 'Single-Threaded, Event-Driven, Non-Blocking I/O' mean in Node.js?

Beginner LevelNode JS

What is the difference between process.nextTick() and setImmediate()?