Skip to content

Instantly share code, notes, and snippets.

@atomize
Forked from montanaflynn/streamer.js
Created August 6, 2022 19:13
Show Gist options
  • Save atomize/48c7cb26cbf3ed236c73fbc698819f2a to your computer and use it in GitHub Desktop.
Save atomize/48c7cb26cbf3ed236c73fbc698819f2a 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