Node: internal module function required?

I was looking at the source code of the command line utility in Node and saw the following code.

function help() { var colors = require('colors'); var package = require('../package'); .... .... } 

I have not seen how I used to be used inside a function. I always thought it was best to include it at the top of the file. This is a recording file for this program, and this function is called only in a specific case, but these packages are used elsewhere in the program. When I asked the author of the code for his reasoning, he simply stated that he "did not want to immediately import all the libraries."

Is this a good / bad practice? Are there significant consequences for loading time without requiring these packages at the top of the module, and instead only when calling these functions?

+5
source share
2 answers

UPDATE: I think the best answer is here: Lazy loading in node.js

MY INITIAL COMMENTS: Well, it's a matter of practice, some guys like it upstairs, and some are lazy. In my opinion, both of them are good and should be used as needed, so I think that the author is here, because loading an entire bundle library at startup will overload the module for the most part that is never used, and therefore increase loading time. Although loading libraries on demand is a synchronous operation, but if we look at the help method as an object, this will give the effect of loading an asynchronous module (see AMD , which is a popular template).

False loading is also a good choice if you need to choose between loading libraries in a particular case, 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 the method is high or even average, then you must demand from above, otherwise, if it is low, it would be nice if the required on module needs a framework.

+5
source

In the case of Node, it really comes down to choosing a style.

Loading a module from disk takes almost no time at all, so there really is nothing like that in terms of increasing performance. Some people like to keep the modules as close as possible to the point where they will be used, that’s all.

Now, the client side, all of it are different and are largely based on your package manager.

+2
source

Source: https://habr.com/ru/post/1244492/


All Articles