Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 534
Connor Black Avatar asked Sep 09 '13 00:09

Connor Black


People also ask

What can be exported from a module?

The module. exports is a special object which is included in every JavaScript file in the Node. js application by default. The module is a variable that represents the current module, and exports is an object that will be exposed as a module.

Can you have more than one module exports?

Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export.

How do you require module exports?

exports object and you want to import these exported constructs in module y, you then need to require the module x in the module y using the require function. The value returned by the require function in module y is equal to the module. exports object in the module x.

What is the difference between exports and module exports?

When we want to export a single class/variable/function from one module to another module, we use the module. exports way. When we want to export multiple variables/functions from one module to another, we use exports way. 2.


2 Answers

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.

like image 103
SLaks Avatar answered Sep 30 '22 12:09

SLaks


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.

like image 36
hurrymaplelad Avatar answered Sep 30 '22 13:09

hurrymaplelad