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!!!


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


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

Leave a Reply

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

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

Facebook photo

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

Connecting to %s