Skip to content

Commit d7e9540

Browse files
committed
docs: add server-sent events example
closes #17
1 parent 1d845f9 commit d7e9540

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

README.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@
66

77
Node.js compression middleware.
88

9+
## Install
10+
11+
```bash
12+
$ npm install compression
13+
```
14+
915
## API
1016

1117
```js
@@ -33,6 +39,51 @@ app.use(compression({
3339

3440
In addition to these, [zlib](http://nodejs.org/api/zlib.html) options may be passed in to the options object.
3541

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+
3687
## License
3788

3889
The MIT License (MIT)

0 commit comments

Comments
 (0)