MadLittleMods
11/14/2017 - 7:02 PM

Barebones Express app for essentially multiple responses from one request (progress)

Barebones Express app for essentially multiple responses from one request (progress)

const express = require('express');
const logger = require('morgan');


const app = express();
app.use(logger('dev'));


app.get('/', function (req, res) {
  res.status(200).send(`
    <p>
      Open the devtools console
    </p>

    <script>
    let currentStreamIndex = 0;

    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://localhost:7897/some-stream', true);
    xhr.onprogress = function() {
      const resText = xhr.responseText;
      console.log(\`CHUNK: \${resText.substr(currentStreamIndex, resText.length)}\`);

      currentStreamIndex = resText.length
    }
    xhr.send();
    </script>
  `);
});

app.get('/some-stream', function (req, res) {
  res.writeHead(200, {
    'Content-Type': 'application/json',
    'Transfer-Encoding': 'chunked'
  });

  // Heartbeat every 30s to keep-alive
  setInterval(function() {
    res.write(' \n');
    res.emit('drain');
  }, 30 * 1000);

  setInterval(function() {
    res.write(JSON.stringify({ foo: 9999 * Math.random() }) + '\n');
    res.emit('drain');
  }, 3 * 1000);

});



const port = 7897;
app.listen(port, function () {
  console.log(`Server listening on ${port}`);
});