Node.js Course
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?

Flash Cards

Question

How many times does it execute?

Click to reveal answer
Answer

Exactly once! The first time it is required, the code runs and the `module.exports` object is stored in memory. The second time, Node just returns the cached object immediately.

Question

How do you clear the cache?

Click to reveal answer
Answer

In CommonJS, you can literally delete the cache key: `delete require.cache[require.resolve('./module.js')]`. The next time it is required, it will execute from scratch. (ES Modules do not currently support cache busting easily).