From d7e954089597265cb27f9130dfeb41f9d93b1687 Mon Sep 17 00:00:00 2001 From: Douglas Christopher Wilson Date: Sun, 20 Jul 2014 22:51:27 -0400 Subject: [PATCH] docs: add server-sent events example closes #17 --- README.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/README.md b/README.md index 5a1b6bbb..9cdb2fb3 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,12 @@ Node.js compression middleware. +## Install + +```bash +$ npm install compression +``` + ## API ```js @@ -33,6 +39,51 @@ app.use(compression({ In addition to these, [zlib](http://nodejs.org/api/zlib.html) options may be passed in to the options object. +### res.flush + +This module adds a `res.flush()` method to force the partially-compressed +response to be flushed to the client. + +## Examples + +### Server-Sent Events + +Because of the nature of compression this module does not work out of the box +with server-sent events. To compress content, a window of the output needs to +be buffered up in order to get good compression. Typically when using server-sent +events, there are certain block of data that need to reach the client. + +You can achieve this by calling `res.flush()` when you need the data written to +actually make it to the client. + +```js +var compression = require('compression') +var express = require('express') + +var app = express() + +// compress responses +app.use(compression()) + +// server-sent event stream +app.get('/events', function (req, res) { + res.setHeader('Content-Type', 'text/event-stream') + res.setHeader('Cache-Control', 'no-cache') + + // send a ping approx eveny 2 seconds + var timer = setInterval(function () { + res.write('data: ping\n\n') + + // !!! this is the important part + res.flush() + }, 2000) + + res.on('close', function () { + clearInterval(timer) + }) +}) +``` + ## License The MIT License (MIT)