1

How do I realise early flush (chuncked transfer encoding) with Express?

All examples I have found are dealing with the http module, where you can call the write() method of the response object and that way send data piece-wise.

  • 1
    The answer given and accepted in this is exactly what I am not looking for. –  Jan 05 '14 at 21:00
  • it pretty much tells you the same thing as the actual answer you got. `res` is still the http module's stream, so you can just use a `res.write` to send a chunk, which it tells you. If this is not what you want, you'll need to update your post to explain you already tried `res.write` and didn't get the result you expected. Some code would help. – Mike 'Pomax' Kamermans Jan 06 '14 at 10:19

1 Answers1

3

You can still use write with Express:

app.get('/test', function(req, res) {
  var count     = 0;
  var interval  = setInterval(function() {
    if (count++ === 5) {
      clearInterval(interval);
      res.end();
      return;
    }
    res.write('This is line #' + count + '\n');
  }, 1000);
});

EDIT: for proper chunked transfer encoding, make sure the set the transfer-encoding header appropriately:

res.setHeader('transfer-encoding', 'chunked');
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • 5
    This isn't working for me... my XMLHttpRequest is not getting any progress events after even write completes... – Michael May 25 '17 at 22:10
  • 1
    data from res.write is not reaching until end is called. So it defies the purpose of getting chunk at client side. – Shiv Dec 29 '20 at 09:49
  • 1
    @Shivam data from `res.write()` is sent down the connection immediately, it isn't stored or saved by Express until `end` is called. But proper chunked transfer encoding requires the `transfer-encoding` header to be set. See edit. – robertklep Dec 29 '20 at 12:39
  • 1
    I finally found my answer by going [here](https://expressjs.com/en/resources/middleware/compression.html). I was missing the `compression` middleware. The last portion with `Server-Sent Events` explains how to set the headers `res.setHeader('Content-Type', 'text/event-stream')` and `res.setHeader('Cache-Control', 'no-cache')` and then using `res.flush()` after each `res.write({your_data_here})`. – Mr Rogers Mar 24 '23 at 19:52