Created
January 27, 2015 19:38
-
-
Save montanaflynn/6a438f0be606daede899 to your computer and use it in GitHub Desktop.
Streaming a response with Express.js
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
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