How do i stream response in express

前端 未结 3 1591
生来不讨喜
生来不讨喜 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:34

    You don't need a readable stream instance, just use res.write():

    res.write("USERID,NAME,FBID,ACCOUNT,SUBSCRIPTION,PRICE,STATE,TIMEPERIOD\n");
    
    for (var i = 0; i < 10; i++) {
        res.write("23,John Doe,1234,500,SUBSCRIPITON,100,ACTIVE,30\n");
    }
    
    res.end();
    

    This works because in Express, res is based on Node's own http.serverResponse, so it inherits all its methods (like write).

    0 讨论(0)
  • 2020-12-08 20:41

    I needed to stream a response in express in order to work with tar-stream. Here is how I did it in case it helps anyone.

    The requests are for a single file from a tar file stored on the server.

    const fs = require("fs"),
       tar = require("tar-stream");
    
    app.get("/fileFromTar/*", (req, res) => {
       const fileWanted = req.params[0],
          readStream = fs.createReadStream('myTarFile.tar'),
          extractor = tar.extract();
    
       extractor.on('entry', (header, stream, next) => {
          stream.on('end', next);
    
          if (header.name === fileWanted) {
             const { size } = header;
             res.set({
               "Content-Type": 'audio/flac', // or whichever one applies
               "Content-Length": size,
               "Content-Range": `bytes 0-${size}/${size}`
             });
             stream.pipe(res);
          }
          else stream.resume();
       });
       readStream.pipe(extractor);
    });
    
    0 讨论(0)
  • 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)
      };
    };
    
    0 讨论(0)
提交回复
热议问题