Node.js
/Advanced
Module Caching
Definition
An internal optimization in Node.js where modules are cached in memory after the first time they are loaded. Subsequent `require()` or `import` calls for the same file return the cached version instead of executing the file again.
Explain Like I'm New
If File A requires 'database.js', Node runs the database script, connects to the DB, and caches the result. If File B later requires 'database.js', Node DOES NOT run the script again. It just hands File B the exact same connection object it gave File A. It's a built-in Singleton!
Real World Example
Creating an `api.js` file that sets up an Axios instance with an Auth Token. Any other file that imports `api.js` gets that exact same, pre-configured Axios instance thanks to caching.
Common Use Cases
- •Sharing state across files without global variables
- •Database connection singletons
- •Performance optimization
Interactive Example
Loading...
Console output will appear here...
Interview Questions
basic
- If you require a file twice, how many times does its code execute?
intermediate
- How does module caching help create Singletons?
advanced
- How do you clear or bust the CommonJS module cache?