require node modules at the file beginning

2019-07-11 23:48发布

问题:

I had a habit of requiring all my node modules in the beginning of the app.js file.

var express=require('express'),
bodyParser = require( 'body-parser' ),
cookieParser = require( 'cookie-parser' ),
compression = require( 'compression' ),
.
.

But some modules are used for single jobs in a single function, so I can remove those from the beginning and place them inline.

var express=require('express'),
bodyParser = require( 'body-parser' ),
cookieParser = require( 'cookie-parser' ),
compression = require( 'compression' ),
.
.
function myfunc(){
require( 'https' ).get( "https://www.google.com/recaptcha/api/siteverify?secret= ......
.
.

instead of

var express=require('express'),
bodyParser = require( 'body-parser' ),
cookieParser = require( 'cookie-parser' ),
compression = require( 'compression' ),
https=require('https'),
.
.
function myfunc(){
https.get( "https://www.google.com/recaptcha/api/siteverify?secret= ......
.
.

My question: Which of these gives better performance?

回答1:

Modules Caching concept inside node.js says:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Documentation can be seen here modules_caching

It means either choice of require is just different way of coding style.



回答2:

The require function is an synchronous operation. Which means that is blocking. It is better to use it in the beginning of your file in order to avoid blocking calls while your program runs. If a module is already required then it is cached so that operation won't be blocking. But most of the times it is preferable to use require on top of your module. This way you don't need to keep track of modules that have been cached in order to use require inside a function without side effects