Facebook Pixel

What is module caching in Node.js?

Modules run once and are cached after first require. This enables singletons for shared state like database connections, but means requiring the same file twice returns the same object. Export a factory function for fresh state on each use.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Node.js Modules Interview Questions With Answers

exports is a reference to module.exports initially. You can add properties to exports or reassign module.exports. Mixing both breaks the link, since reassigning module.exports makes exports point to the old object. Pick one approach per file.

require reads a file, runs it once, caches the result, and returns the file's module.exports. Subsequent requires return the cached object without re-running the file, so a module's code runs once.

CommonJS uses require and module.exports, is synchronous, and loaded at runtime. ES modules use import and export, are async, and statically analyzable. Pick one per project to avoid mixing issues.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.