Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Created January 27, 2015 19:38
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save montanaflynn/6a438f0be606daede899 to your computer and use it in GitHub Desktop.
Save montanaflynn/6a438f0be606daede899 to your computer and use it in GitHub Desktop.
Streaming a response with Express.js
var express = require('express')
var app = express()
app.listen(1337)
app.all('/stream/:chunks', function (req, res, next) {
res.writeHead(200, {
'Content-Type': 'text/plain',
'Transfer-Encoding': 'chunked'
})
// set default chunks to 10
var chunks = req.params.chunks || 10
// max out chunks at 100
if (chunks > 100) chunks = 100
var count = 1
while (count <= chunks) {
res.write(JSON.stringify({
type: "stream",
chunk: count++
})+'\n')
};
res.end()
next()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment