@@ -180,6 +180,36 @@ fewer calls to zlib, since it'll be able to process more data in a |
180 | 180 | single `write` operation. So, this is another factor that affects the |
181 | 181 | speed, at the cost of memory usage. |
182 | 182 |
|
| 183 | +## Flushing |
| 184 | + |
| 185 | +Calling [`.flush()`][] on a compression stream will make zlib return as much |
| 186 | +output as currently possible. This may come at the cost of degraded compression |
| 187 | +quality, but can be useful when data needs to be available as soon as possible. |
| 188 | + |
| 189 | +In the following example, `flush()` is used to write a compressed partial |
| 190 | +HTTP response to the client: |
| 191 | +```js |
| 192 | +const zlib = require('zlib'); |
| 193 | +const http = require('http'); |
| 194 | + |
| 195 | +http.createServer((request, response) => { |
| 196 | + // For the sake of simplicity, the Accept-Encoding checks are omitted. |
| 197 | + response.writeHead(200, { 'content-encoding': 'gzip' }); |
| 198 | + const output = zlib.createGzip(); |
| 199 | + output.pipe(response); |
| 200 | + |
| 201 | + setInterval(() => { |
| 202 | + output.write(`The current time is ${Date()}\n`, () => { |
| 203 | + // The data has been passed to zlib, but the compression algorithm may |
| 204 | + // have decided to buffer the data for more efficient compression. |
| 205 | + // Calling .flush() will make the data available as soon as the client |
| 206 | + // is ready to receive it. |
| 207 | + output.flush(); |
| 208 | + }); |
| 209 | + }, 1000); |
| 210 | +}).listen(1337); |
| 211 | +``` |
| 212 | + |
183 | 213 | ## Constants |
184 | 214 |
|
185 | 215 | <!--type=misc--> |
@@ -409,4 +439,5 @@ Decompress a Buffer or string with Unzip. |
409 | 439 | [Inflate]: #zlib_class_zlib_inflate |
410 | 440 | [InflateRaw]: #zlib_class_zlib_inflateraw |
411 | 441 | [Unzip]: #zlib_class_zlib_unzip |
| 442 | +[`.flush()`]: #zlib_zlib_flush_kind_callback |
412 | 443 | [Buffer]: buffer.html |