Node.JS

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();

Node notes : on require with no js file in local path

Posted on

if you require, for example  “greet”, and greet.js is not found, node will look for folder called “greet” and then look for a file called index.js