require node modules at the file beginning

▼魔方 西西 提交于 2019-12-23 23:14:54

问题


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



来源:https://stackoverflow.com/questions/36660713/require-node-modules-at-the-file-beginning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!