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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With