Reputation: 14554
will require() in nodejs load one copy of module or multi copy? The reason I ask this question is because I'd like to use following code to load some file and cache it in memory.
var fs = require('fs');
var htmlString = '';
var cssString = '';
var jsString = '';
if(!htmlString) {
htmlString = fs.readFileSync(__dirname + '/invoiceTpl/default/invoice.html', 'utf8');
}
if(!cssString) {
cssString = fs.readFileSync(__dirname+ '/invoiceTpl/default/css/invoice.css', 'utf8');
}
if(!jsString) {
jsString = fs.readFileSync(__dirname + '/invoiceTpl/default/js/invoice.js', 'utf8');
}
module.exports = {
html: htmlString,
css: cssString,
js: jsString
};
I'd like to create a closure. So only load the file from disk if the string is empty.
This module is required at many other places. Do you think nodejs will use one copy of the module, therefore only reading from disk once, or multiple loading multiple times, as much time as I require this module, and therefore caching doesn't help?
Upvotes: 0
Views: 520
Reputation: 14659
Their is a cache located in the global object, (require.cache
), so if you have a file called a.js
located in the current directory.
And then call this multiple times:
require('./a');
require('./a');
It will be checked in from require.cache
before being attempted to load, so any thing changed in a.js in between those require statements won't have any effect in your current process.
So, it will hold one copy per process.
Try it yourself. Open up the node shell, require a module, then change something in the file, then require it again and then call the function again. Nothing will change.
Upvotes: 1