node notes: require() caches module.exports

Posted on Updated on

if you are importing a file that instantiates a new object

when you import the file again as a 2nd object you would expect … a new object

but your 2nd variable will be the same object as the first variable, even though a “new” constructor was used. why?

Node caches module imports , it wont load the file again so no new instance!!!

example:

// file greet3.js
function Greetr(){
  this.greeting=”Hello World from greet3″
  this.greet=function(){console.log(this.greeting)}
}
module.exports = new Greetr();

 

//app.js
var greet3 = require(“./greet3.js”);
greet3.greet();
greet3.greeting = “NEW GREETING!!!!”
var greet3a = require(“./greet3.js”);
greet3a.greet();
//console.log
Hello World from greet3
NEW GREETING!!!!
how to resolve??
in the file being exported, greet3.js, send the constructor not the new instance
//greet3.js
module.exports = Greetr;
//app.js
var Greet3a = require(“./greet3.js”);  //you capitalize greet3a to tell its constructor
var grtr = new Greet3a();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s