Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.