Facebook Pixel

How does module.exports work in Node.js?

module.exports is an object Node.js gives every file. Whatever you assign to it becomes what require returns when another file requires this one. You can export a single value by assigning directly, or multiple values with exports.add.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How module.exports and require Work in Node.js

require takes a file path, runs that file, and returns its module.exports. The file's code runs once and is cached, so requiring the same file twice returns the same object, not a fresh copy.

Mixing exports.add and module.exports = in the same file. exports is a reference to module.exports initially, but reassigning module.exports breaks the link. Pick one approach per file to avoid bugs.

Yes. Modules run once and are cached after their first require. Requiring the same file twice returns the same object. If you need fresh state, export a factory function that creates new state, not a shared object.

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.