In this post, I am talking about caching of Modules in NodeJS.
We have the following files
node app.js, on first glance, we’d expect the output to be:
Our logic is that
greet2.greet() would print “Heyyyyyy?” because it’ll get a fresh copy of module.export from greet.js file.
But on the contrary, the output of the above program is:
So what actually happens is that – when
greet1 function calls
require("./module/greet")function, a new module for
greet.jsis created and compiled. After compilation and before returning node stores the cached copy of
module.exports in the variable
cachedModule.exports, and then returns
cachedModule.exportspoints towards the same location in memory where
greet1 points at. Now when we made a change to
greet1 by mutating the
cachedModule.exports too changes because ultimately both
greet1 are the same. They point to the same object.
So now when
greet2 calls the
require("./module/greet")function, instead of recompiling
greet.js, node checks if there’s a cached copy of
module.exports.If found, it returns it and hence saves time which would’ve got lost in recompiling
greet2 essentially gets the same object which is pointed towards by
greet1. This is the reason
Node also provides a feature to delete the stored cache. It’s done by executing the following statement:
So if one wants to always reload the module, he can add this function:
Takeaways from this lesson:
Whenever a module is required, node checks if there exists cached copy of its module.exports. If exists it returns the cached copy, otherwise it compiles that module and makes cached copy of its module.exports and then returns module.exports.