I'm learning KOA and Node.JS streams.
What I'm trying to do is sending a partial HTTP response, and after a short while send the rest of the response.
app.get("/", function*(next) {
// TEST:
function delay(ms) {
return function(callback) {
setTimeout(callback, ms);
}
}
this.type = "text/plain";
var Readable = require("stream").Readable;
var stream = this.body = new Readable();
stream._read = function () {};
stream.push('First line.\n');
yield delay(2000);
stream.push('Last line.\n');
stream.push(null);
console.log("done");
});
I'd expect that while loading the page in the browser, "First line." is immediately displayed and after 2 seconds also "Second line". Instead, it seems that the response is sent as a whole.
What am I missing here?
In the end I wand to stream internally generated logging data in a long-living connecton to the browser.
Node 0.11.3 with Koa 0.10.0
Stream is piped later, you don't have a chance to flush data inside the function.
Check the code:
var koa = require('koa')
var Readable = require('stream').Readable
var app = koa()
app.use(function*(next){
this.type = 'text/plain'
var stream = this.body = new Readable()
stream._read = function () {}
// isn't piped
console.log(stream._readableState.pipes != null)
yield function (callback) { setTimeout(callback, 2000) }
// not yet
console.log(stream._readableState.pipes != null)
var i = 0
setTimeout(function f(){
if (i == 0)
// now it is
console.log(stream._readableState.pipes != null)
stream.push(Date() + '\n');
if (++i < 200)
setTimeout(f, 50)
else
stream.push(null)
}, 100)
})
app.listen(80)
Now, I'm not too familiar with koa, so another solution may exist.