Tuesday, November 5, 2019

NodeJs: Module caching

In NodeJs, whenever we import a module by using require() statement, the corresponding module object is get cached after the first time it is loaded. Now own-wards, if we reload the same module even in different file, we will get a cached copy of the module provided "require.cache" is not modified( has been discussed very clearly in https://bambielli.com/til/2017-04-30-node-require-cache/ ).

This can be understood by following example. Here, I am using 4 classes:

1) my-module.js
class myModule {
constructor(myName) {
this.myName = myName;
}
setName(name) {
this.myName = name;
}
}
module.exports = new myModule("defaultName");
Here, my-module is having a field "myName" with default value as "defaultName". This field can be changed either by constructor or by function setName()

2) my-class1.js
var myModule = require('./my-module');
class myClass1 {
getName() {
console.log("Value of myName in myClass1 object = "+myModule.myName);
}
changeName(newName) {
myModule.setName(newName);
}
}
module.exports = myClass1;
Here, my-class1.js is importing the module "my-module" and having two functions like getName() and changeName() to print/change value of myName field of "my-module"

3) my-class2.js
var myModule = require('./my-module');
class myClass2 {
getName() {
console.log("Value of myName in myClass2 object = "+ myModule.myName);
}
}
module.exports = myClass2;
Here, it is importing same module i.e. "my-module", but having only one function getName() to print the myName field of "my-module". So, by default the function getName() should print here default value of myName field i.e. "defaultName"

4) test-class.js
var myClass1 = require('./my-class1');
var myClass1Obj = new myClass1();
myClass1Obj.changeName("Jitendra");
myClass1Obj.getName();

var myClass2 = require('./my-class2');
var myClass2Obj = new myClass2();
myClass2Obj.getName();
Here, we are first importing my-class1 and creating its object. Then through this object we are changing the default value of myName field of "my-module" and then printing the value of myName field.

After this, we are importing my-class2 and creating its object and just printing the value of myName field. Here, the value printed is same as the value printed by myClass1 object. That means both my-classs1 and my-class2 are having the same object of "my-module"  although both the classes are separately importing that module.

So here the class my-class1 is first importing the my-module and then object of my-module is getting cached and when my-class2 is going to import the same module, its getting the cached object of my-module instead of fresh new object.

If we run test-class.js by node command like "node test-class", we will get output like:

Value of myName in myClass1 object = Jitendra
Value of myName in myClass2 object = Jitendra

No comments:

Post a Comment

Please provide your precious comments and suggestion