aickin / shrink-ray

Node.js compression middleware
MIT License
268 stars 21 forks source link

Adding callback to res.write and res.end for streaming support #1

Closed jpodwys closed 8 years ago

jpodwys commented 8 years ago

I want to be able to use compression to enable GZIP on streamed responses that flush multiple chunks to the browser whenever the implementer wants. (This is especially useful when implementing a BigPipe algorithm such as with my express-stream library.) As a result, I need a sure way of flushing only after a chunk of output has been zipped.

Currently, the following code encounters a race condition because res.write is not blocking. As a result, it's possible that res.flush will execute before res.write completes.

res.write(html);
if(res.flush) res.flush();

I've confirmed the above by ensuring this works as expected:

res.write(html);
setTimeout(function(){
  if(res.flush) res.flush();
}, 10);

What I'd prefer to do, and what this PR enables, is the following:

res.write(html, null, function(){
  if(res.flush) res.flush();
});
jpodwys commented 8 years ago

I've made the same PR to the original compression as well. Doug and I are having some good discussion about it. Perhaps wait on this PR until Doug and I decide how best to accomplish my goal. Thanks for the awesome work!