0

I have a very simple node.js server that I use to ping some servers I need to keep online.

Using Express I have a very simple endpoint I can access that will perform a loop of requests and report the results.

Using res.write() on each loop, the webpage I load can show me the progress as it's happening.

The problem is, this progress doesn't happen in Safari on either OS X or iOS. It waits until the process is complete and then dumps the whole output in 1 go.

Here's an example of my code:

router.route('/test').get(function(req, res)
{
    res.write('<html><head></head><body>');
    res.write('Starting tests...<br />');
    performServerTests(req, res, function(results)
    { // Each loop within performServerTests also uses res.write()
        res.write('<br />Complete');
        res.end('</body></html>');
    });
});

Is there a known reason why Safari would wait for the res.end() call before displaying what it already has, while Chrome shows each res.write() message as it receives it?

Thanks

Darren
  • 10,182
  • 20
  • 95
  • 162

1 Answers1

3

When using chunked transfers (what you're trying to do), browsers are generally waiting for a minimum amount of data to be received before starting rendering. The exact size is browser-specific - see Using "transfer-encoding: chunked", how much data must be sent before browsers start rendering it? for some quite recent data points on this. You example could for example be written like this (adding some headers to be explicit too):

router.route('/test').get(function(req, res)
{
    res.setHeader('Content-Type', 'text/html; charset=UTF-8');
    res.setHeader('Transfer-Encoding', 'chunked');
    res.write('<html><head></head><body>');
    res.write('Starting tests...<br />');
    var buf = ""
    for (var i = 0; i < 500; i++) {
        buf += " "
    }
    res.write(buf);
    performServerTests(req, res, function(results)
    { // Each loop within performServerTests also uses res.write()
        res.write('<br />Complete');
        res.end('</body></html>');
    });
});
Community
  • 1
  • 1
Guitan
  • 375
  • 2
  • 4
  • Thanks for your explanation Guitan. You where spot on. Safari just needed a bit more data before it started displaying. – Darren Sep 10 '15 at 13:22