I was browsing the source code for a command line utility in Node, and saw the following code.
function help() {
var colors = require('colors');
var package = require('../package');
....
....
}
I had not seen require being used inside a function in this way before. I always assumed it was best practice to include it at the top of the file. This is the entry file for this program, and this function is only called in a specific case--but those packages are used elsewhere in the program. When I asked the author of the code for his reasoning, he simply stated that he "didn't want to import all the libraries at once."
Is this good/bad practice? Are there significant implications to load-up time by not requiring these packages at the top of the module, and instead only when these functions are invoked?
1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
Node js. Answer: require();
Each module in Node. js has its own context, so it cannot interfere with other modules or pollute global scope. Also, each module can be placed in a separate . js file under a separate folder.
If the module is native, it calls the NativeModule. require() with the filename and returns the result. Otherwise, it creates a new module for the file and saves it to the cache. Then it loads the file contents before returning its exports object.
UPDATE: I think a better answer is here: Lazy loading in node.js
MY INITIAL COMMENTS:
Well it's a matter of practice, some guys like it at the top while some like lazy-loading. In my opinion both are good, and should be used as per need, so I think that author is right here, because loading a whole bunch libraries at the startup would overload the module with much of the stuff that is never used, and hence would increase the load-time. And although loading the libraries on demand is a synchronous operation, but if we look help
method as an entity, then it would give an asynchronous module loading effect (see AMD, which is a popular pattern).
Lazy loading is also a good selection if you have to make a choice between which libraries to load in a particular case, like for example
var isOSX;
// some code here which finds if this is OSX
// then this
if (isOSX === true) {
var platformHelper = require('supercoolosxhelper');
} else {
var platformHelper = require('yetanothercoolhelper');
}
In short, you should anticipate in your code if the probability of using a method is high or even mid, then you should require at the top, otherwise if it's low then it would be nice if the module is required
on need basis.
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