So I'm planning to separate my functions into separate files and then import them into a single index.js
which then becomes the main exporter. So I'm wondering if having something like var bcrypt = require('bcrypt')
in several of my files be slower than just having it in one file.
Here's how I'm planning to group and export in index.js
const fs = require('fs');
const path = require('path')
const modules = {}
const files = fs.readdirSync(__dirname)
files.forEach(file => {
if (file === 'index.js') return
let temp = require(path.join(__dirname, file))
for (let key in temp) {
modules[key] = temp[key]
}
});
module.exports = modules
As an example of what I mean:
file1.js
var bcrypt = require("bcrypt");
module.exports.file1test = "hi"
file2.js
var bcrypt = require("bcrypt");
module.exports.file2test = "bye"
In the end requiring that module in a function vs at the top of a module consumes the same amount of memory, but requiring at the top of a module means it will always be ready to go when someone requests that route and you would instead factor that extra 30 minuets into your deployment time, not at 3am in the morning ...
The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.
No, it does not. Whenever a module is require
d for the first time, the module's code runs, assigns something to its exports, and those exports are returned. Further require
s of that module simply reference those exports again. The logic is similar to this:
const importModule = (() => {
const exports = {};
return (name) => {
if (!exports[name]) exports[name] = runModule(name);
return exports[name];
};
})();
So, multiple import
s of the same module is no more expensive than referencing an object multiple times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With