NodeJs网站TTFB非常高,网站运行速度非常慢

时间:2016-03-31 06:39:52

标签: node.js express pug

我在nodejs中使用Express& amp;创建了一个网站。玉。 当我加载内容非常少的简单登录页面时,即使这样,它也需要花费很多时间来加载。 它的TTFB太高了(参考截图附件。) enter image description here 下面是我的app.js代码。不确定我做错了什么。

app.js

// Packages
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dbhelper = require('./routes/dbhelper.js')
var common = require('./routes/common.js')
var session = require('express-session')
var http = require('http');

var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
}))

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
//app.locals.basedir = path.join(__dirname, 'views');

// set up mustbe config
var mustBe = require("mustbe");
var mustBeConfig = require("./mustBeConfig");
mustBe.configure(mustBeConfig);

// Routes
var routes = require('./routes/index');
var users = require('./routes/users');
var dashboard = require('./routes/dashboard');
var monitor = require('./routes/monitor');
var resetpassword = require('./routes/resetpassword');
var archive = require('./routes/archive');
var archiveList = require('./routes/archiveList');
var archiveSetup = require('./routes/archivesetup');


app.locals.moment = require('moment');

app.use(function (req, res, next) {
    res.locals.session = session;
    next();
});


// Make database connection available to router
app.use(function (req, res, next) {
    req.sessionID = req.sessionID;
    req.db = dbhelper.sql;
    req.config = dbhelper.config;
    req.ActionOutput = common.ActionOutput;
    req.ActionStatus = common.ActionStatus;
    req.ChangeEmployer = common.ChangeEmployer;
    // Redirect to login page if no session found
    if ((session.Employee == null || session.Employee == undefined || session.Employee == '') && (req.url != '/' && req.url != '' && req.url != '/login'))
        res.redirect('/');
    // Redirect to dashboard if session exists & redirecting to login page
    else if ((session.Employee != null && session.Employee != undefined && session.Employee != '') && (req.url == '/' || req.url == '' || req.url == '/login'))
        res.redirect('/dashboard');
    else
        next();
});



app.use('/', routes);
app.use('/users', users);
app.use('/dashboard', dashboard);
app.use('/monitor', monitor);
app.use('/resetpassword', resetpassword);
app.use('/archive', archive);
app.use('/archiveList', archiveList)
app.use('/archivesetup', archiveSetup);


process.on('uncaughtException', function (err) {
    console.log('Caught exception: ${ err}');
    var EID = SaveErrorLog(err.message, err.stack, 'a', err.address);
});


app.use(function (err, req, res, next) {
    if (!err)
        return next();
    var EID = SaveErrorLog(err.message, err.stack, req.connection.remoteAddress , err.path);
    // Check if request is ajax
    var is_ajax_request = req.xhr;

    var op = new common.ActionOutput();

    op.ActionStatus = common.ActionStatus.Error;
    op.Message = err.message;
    res.send(op);
});

function SaveErrorLog(Message, CompleteError, IP, URL) {
    // Get Logged In User
    var UserID = null;
    if (session.SupportUser != null && session.SupportUser != undefined && session.SupportUser != '') {
        UserID = session.SupportUser.UserID;
    } else if (session.Employee != null && session.Employee != undefined && session.Employee != '') {
        UserID = session.Employee.EmployeeID;
    }
    // Log Error Into Database 
    var ErrorLogID = 0;
    var sql = dbhelper.sql;
    var conn = new sql.Connection(dbhelper.config);
    conn.connect().then(function () {
        // Stored Procedure 
        var request = new sql.Request(conn);
        request.input('UserID', sql.BigInt, UserID);
        request.input('Message', sql.VarChar(500), Message);
        request.input('CompleteError', sql.VarChar(2000), CompleteError);
        request.input('IP', sql.VarChar(50), IP);
        request.input('URL', sql.VarChar(50), URL);
        request.execute('USP_SaveErrorLog', function (err, recordset, returnValue) {
            if (!err && recordset[0][0].ValidationCode == null) {
                ErrorLogID = recordset[0][0].ErrorLogID;
            } else {

            }
            return ErrorLogID;
        });
    });
}

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('shared/error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('shared/error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

//app.listen(1234, function () {
//    console.log('Server starts on port: ' + 1234);
//});

http.createServer(app).listen(1234, function () {
    console.log('Express server listening on port ' + 1234);
});

我还从app.js中删除了所有与数据库相关的工作,但仍面临同样的问题。 任何帮助都会很明显。

1 个答案:

答案 0 :(得分:2)

我们使用过这样的东西,它会缓存玉器内容并减少TTFB

/* GET home page. */
router.get('/', function (req, res) {
    var abs = session.Employers;
    var options = {cache: true , title: 'Express'};

    //Method 1
    //var template = jade.compileFile('./views/login/index.jade', options);
    //res.send(template({ title: 'Express' }));

    //Method 2
    res.send(jade.renderFile('./views/login/index.jade', options));

});