Jitendra Pancholi Jitendra Pancholi - 5 months ago 64
Node.js Question

NodeJs website TTFB is very high and site is running very slow

I have created a website in nodejs with Express & Jade.
When i load the simple login page with very less content, even then it taking is much time to load.
It's TTFB is too high (ref to screenshot attached.)
enter image description here
Below is my app.js code. Not sure what i'm doing wrong.

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);
});


I have also removed all database related work from app.js but still facing same issue.
Any help would be appreciable.

Answer

We have used something like this, it will cache jade content and reduce 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));

});
Comments