|
6 | 6 |
|
7 | 7 | Node.js compression middleware. |
8 | 8 |
|
| 9 | +## Install |
| 10 | + |
| 11 | +```bash |
| 12 | +$ npm install compression |
| 13 | +``` |
| 14 | + |
9 | 15 | ## API |
10 | 16 |
|
11 | 17 | ```js |
@@ -33,6 +39,51 @@ app.use(compression({ |
33 | 39 |
|
34 | 40 | In addition to these, [zlib](http://nodejs.org/api/zlib.html) options may be passed in to the options object. |
35 | 41 |
|
| 42 | +### res.flush |
| 43 | + |
| 44 | +This module adds a `res.flush()` method to force the partially-compressed |
| 45 | +response to be flushed to the client. |
| 46 | + |
| 47 | +## Examples |
| 48 | + |
| 49 | +### Server-Sent Events |
| 50 | + |
| 51 | +Because of the nature of compression this module does not work out of the box |
| 52 | +with server-sent events. To compress content, a window of the output needs to |
| 53 | +be buffered up in order to get good compression. Typically when using server-sent |
| 54 | +events, there are certain block of data that need to reach the client. |
| 55 | + |
| 56 | +You can achieve this by calling `res.flush()` when you need the data written to |
| 57 | +actually make it to the client. |
| 58 | + |
| 59 | +```js |
| 60 | +var compression = require('compression') |
| 61 | +var express = require('express') |
| 62 | + |
| 63 | +var app = express() |
| 64 | + |
| 65 | +// compress responses |
| 66 | +app.use(compression()) |
| 67 | + |
| 68 | +// server-sent event stream |
| 69 | +app.get('/events', function (req, res) { |
| 70 | + res.setHeader('Content-Type', 'text/event-stream') |
| 71 | + res.setHeader('Cache-Control', 'no-cache') |
| 72 | + |
| 73 | + // send a ping approx eveny 2 seconds |
| 74 | + var timer = setInterval(function () { |
| 75 | + res.write('data: ping\n\n') |
| 76 | + |
| 77 | + // !!! this is the important part |
| 78 | + res.flush() |
| 79 | + }, 2000) |
| 80 | + |
| 81 | + res.on('close', function () { |
| 82 | + clearInterval(timer) |
| 83 | + }) |
| 84 | +}) |
| 85 | +``` |
| 86 | + |
36 | 87 | ## License |
37 | 88 |
|
38 | 89 | The MIT License (MIT) |
|
0 commit comments