Node.js Express Jade改进了TTFB?

时间:2015-05-03 19:17:39

标签: javascript node.js express

我试图从PHP / Nginx切换到NodeJS Express Jade并且​​我创建了一个app.js,其中包含运行NodeJS网站所需的所有代码,问题是TTFB每个需要大约1秒钟时间,我使用GZIP和缓存。您可以在下面找到我的app.js代码

var express          = require('express'); 
var subdomain        = require('express-subdomain');
var compression      = require('compression');
var fs               = require('fs');
var path             = require('path');
var mime             = require('mime-types');
var app              = express();
var router           = express.Router();
app.set('views',__dirname+'/views');
app.set('view engine','jade');

app.use(subdomain('cdn',router));
app.use(compression({level:9}));

router.get('*',function(req,resp,next){
    CDNDeliver(__dirname+'/cdn/'+req.url,function(data)
    {
       resp.header("Access-Control-Allow-Origin", "*");
       resp.contentType(mime.contentType(path.extname(__dirname+'/cdn'+req.url)));
       resp.end(data);
    });
});

app.get('/',
        function(req,resp)
        {
            RenderView(resp,'index',
                        function(html)
                        {

                            resp.end(html);
                        }
                      );
        }
);

app.listen(80,function()
        {
            console.log('node.js started');
        }
);


var ViewCache = {}; 
function RenderView(resp,view,callback) {
   if(!ViewCache[view])
   {
      ViewCache[view] = resp.render(view);
      callback(ViewCache[view]);
   }
   else
      callback(ViewCache[view]);
}
var CDNCache = {};
function CDNDeliver(url,callback)
{
    if(!CDNCache[url])
    {
      fs.readFile(url,function(err,data)
        {
           if(!err)
              CDNCache[url]=data;
              callback(CDNCache[url]);
        })
    }
    else
    callback(CDNCache[url]);
}

LoadTime

任何人都可以解释为什么TTFB如此之高,或者我如何减少它?

1 个答案:

答案 0 :(得分:-1)

您可以通过从开发切换到生产来减少TTFB。设置:

NODE_ENV=production