How does module caching work in Node.js?
When you require a file, Node.js runs it once and stores its module.exports in a cache. Subsequent requires of the same file return the cached object without running the file again, so a module's code runs once.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Node.js Module Caching Explained: How require Caches Modules
Because it means a module's code runs once, and every file that requires it sees the same value. This is useful for shared state like database connections and configuration, and enables the singleton pattern without extra code.
Yes. A module that exports a single object acts as a singleton, since every require returns the same cached instance. This is how shared database connections and configuration work in Node.js apps.
Export a factory function that creates fresh state, instead of a shared object. Calling the factory on each use gives you independent instances, while the module itself stays cached.
Still have questions?
Browse all our FAQs or reach out to our support team
