How do I get fresh state from a cached module in Node.js?
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.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Node.js Module Caching Explained: How require Caches Modules
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.
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.
Still have questions?
Browse all our FAQs or reach out to our support team
