Last active
September 25, 2018 11:38
-
-
Save MadLittleMods/5ed47aee7a1aca926b450048c4e0b3af to your computer and use it in GitHub Desktop.
Barebones Express app for essentially multiple responses from one request (progress)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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