Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Module Caching
interview

Q1. How does Node.js cache modules?
After a module is loaded the first time, it's cached in require.cache. Subsequent calls to require() for the same module return the cached exports object without reloading the module. This improves performance and ensures singleton-like behavior for modules.

Q2. Why is module caching useful?
Caching prevents repeated execution of module code, saving time and resources. It also allows modules to maintain state across requires (like database connections). For example, if a module exports a configured object, all require calls get the same instance, enabling shared state.

Q3. How can you clear the module cache?
Access require.cache, which is an object mapping resolved filenames to module objects. Delete an entry:
delete require.cache[require.resolve('./module')];
. Then the next require will reload the module. Useful in development for hot-reloading, but not recommended in production.

Q4. Does module caching affect tests?
Yes, caching can cause issues in testing where you want fresh modules for each test. Many testing frameworks clear the cache or use module isolation techniques. You might need to reset module state between tests or use module.parent or import fresh copies.

Q5. How does caching work with node_modules?
The same caching mechanism applies to npm packages. Once a package is loaded, it's cached. However, different versions of the same package are treated as separate modules based on their resolved path. This allows having multiple versions of a package in node_modules.