How do I stream response in express?

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)
  };
};

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).


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);
});