Keep-alive is supposed to speed up the site.
However, when I run this dead simple server in chrome (localhost:8080), I get these loading times:
around 100 ms with the "Connection: close" header (i.e. with setHeader line uncommented)
around 400 ms with the standard keep-alive enabled.
What am I doing wrong ? Can anybody reproduce my result ?
I have been banging my head for the last 2 days on this.
var fs = require('fs')
// preparing 50 2k files ...
var a = [], txt = '/*\n' + 'x'.repeat(2000) + '\n*/'
for (var i = 0; i < 50; i++) {
var name = '/test' + i + '.js'
fs.writeFile(__dirname + name, txt)
a.push('<script src="' + name + '"></script>')
}
fs.writeFile(__dirname + '/index.html', a.join('\n') + '\nhello world')
var serve = function (req, res) {
if (req.url === '/favicon.ico') {
res.statusCode = 404; return res.end()
}
var pth = req.url + (req.url.match(/\/$/) ? 'index.html' : '')
var s = fs.createReadStream(__dirname + pth)
res.on('finish', function () { console.log('done', req.url) })
// THIS IS THE KILLER LINE. Just uncomment and restart the server.
// on my system, the page loads 4 times FASTER
// res.setHeader('Connection', 'close')
res.statusCode = 200; s.pipe(res)
}
require('http').createServer(serve).listen(8080)
EDIT
for clarity, the behaviour is the same when using a standard express server. The following server code will yield the same results (on my system, at least)
// express server code
var express = require('express')
var app = express()
var closeConnection = function (req, res, next) {
res.setHeader('Connection', 'close'); next()
}
// THIS IS THE KILLER LINE. Just uncomment and restart the server.
// on my system, the page loads 4 times FASTER
// app.use('*', closeConnection)
app.use(express.static(__dirname))
require('http').createServer(app).listen(8080)