我习惯在 app.js 文件的开头要求所有 Node 模块。
var express=require('express'),
bodyParser = require( 'body-parser' ),
cookieParser = require( 'cookie-parser' ),
compression = require( 'compression' ),
.
.
但是有些模块用于单个函数中的单个作业,因此我可以从一开始就删除它们并将它们内联放置。
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= ......
.
.
我的问题:其中哪一个可以提供更好的性能?
最佳答案
node.js 中的模块缓存概念说:
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
只是编码风格的不同方式。
关于node.js - 在文件开头需要 Node 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36660713/