Node: requiring module inside function?

Viewed 16298

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?

3 Answers

It has its own pros and cons. But generally you should avoid it. Here is a good explanation why:

First scenario: imagine I had only module a.js and b.js. Module a.js requires b.js and module b.js requires c.js. If they require at the top of the module I will get alerted when I launch my application that module c.js was not found and the server would crash before I ever went to deploy it. If b.js and c.js are required in functions the error may go undetected until the server is deployed, at which time the entire server will crash when Node attempts to load module c.js possibly several days later if the route requiring that module is one rarely used.

Second scenario: imagine I had a module that took 30 minuets to load, which is unreasonable, but just imagine. If that module is only needed in one route handler it might take some time before someone triggers that route and Node has to require that module. When this happens the server would effectively be inaccessible for 30 minutes as that module is loaded. If this happens at peak hours several of my users might become unhappy and leave. 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 when a client calls complaining that their site is down.

Related