How do i stream response in express

前端 未结 3 1597
生来不讨喜
生来不讨喜 2020-12-08 19:55

I\'ve been trying to get a express app to send the response as stream.

var Readable = require(\'stream\').Readable;
var rs = Readable();


app.get(\'/report\         


        
3条回答
  •  北海茫月
    2020-12-08 20:42

    I was able to get this to work.

    • Put this code in your Express router.
    • Open a web browser
    • Go to http://yourdomain/yourrouterpath/stream

    ...

    router.get('/stream', function (req, res, next) {
      //when using text/plain it did not stream
      //without charset=utf-8, it only worked in Chrome, not Firefox
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
      res.setHeader('Transfer-Encoding', 'chunked');
    
      res.write("Thinking...");
      sendAndSleep(res, 1);
    });
    
    
    var sendAndSleep = function (response, counter) {
      if (counter > 10) {
        response.end();
      } else {
        response.write(" ;i=" + counter);
        counter++;
        setTimeout(function () {
          sendAndSleep(response, counter);
        }, 1000)
      };
    };
    

提交回复
热议问题