Connor Black
Connor Black

Reputation: 7181

Module.export-ing a New Instance

If I attach an object to the module.exports object in node like so:

module.exports = new Object()

will each object = require('./Object') throughout my application create a new instance of that object, or will it create a reference to the one instance?

Upvotes: 7

Views: 4456

Answers (2)

hurrymaplelad
hurrymaplelad

Reputation: 27785

Check out caching caveats in the node docs. You'll get the same object as long as the resolved module path matches. There's an example in this answer of when resolved paths would not match.

Upvotes: 1

SLaks
SLaks

Reputation: 887767

require() caches files that it executes.

The first time you require('./Object'), it will run your code and place the exported object in require.cache.
Subsequent calls will return the cached object immediately.

You could remove your module from the cache yourself, or use a getter, but those are bad ideas.

Upvotes: 10

Related Questions