在文件开头需要节点模块 [英] require node modules at the file beginning

查看:49
本文介绍了在文件开头需要节点模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯在app.js文件的开头要求所有节点模块.

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= ......
.
.

代替

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?

推荐答案

node.js中的模块缓存概念说:

Modules Caching concept inside node.js says:

模块在第一次加载后被缓存.这表示 (除其他事项外),每个对require('foo')的调用都会得到 如果解析为相同对象,则返回完全相同的对象 文件.

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.

可以在此处查看文档 modules_caching

这意味着选择require只是一种不同的编码方式.

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

这篇关于在文件开头需要节点模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆