Skip to content

Commit d069f2d

Browse files
addaleaxMyles Borins
authored and
Myles Borins
committed
doc: add full example for zlib.flush()
Add a full example using `zlib.flush()` for the common use case of writing partial compressed HTTP output to the client. PR-URL: #6172 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Robert Jefe Lindstädt <[email protected]>
1 parent 37cc249 commit d069f2d

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

doc/api/zlib.markdown

+31
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,36 @@ fewer calls to zlib, since it'll be able to process more data in a
155155
single `write` operation. So, this is another factor that affects the
156156
speed, at the cost of memory usage.
157157

158+
## Flushing
159+
160+
Calling [`.flush()`][] on a compression stream will make zlib return as much
161+
output as currently possible. This may come at the cost of degraded compression
162+
quality, but can be useful when data needs to be available as soon as possible.
163+
164+
In the following example, `flush()` is used to write a compressed partial
165+
HTTP response to the client:
166+
```js
167+
const zlib = require('zlib');
168+
const http = require('http');
169+
170+
http.createServer((request, response) => {
171+
// For the sake of simplicity, the Accept-Encoding checks are omitted.
172+
response.writeHead(200, { 'content-encoding': 'gzip' });
173+
const output = zlib.createGzip();
174+
output.pipe(response);
175+
176+
setInterval(() => {
177+
output.write(`The current time is ${Date()}\n`, () => {
178+
// The data has been passed to zlib, but the compression algorithm may
179+
// have decided to buffer the data for more efficient compression.
180+
// Calling .flush() will make the data available as soon as the client
181+
// is ready to receive it.
182+
output.flush();
183+
});
184+
}, 1000);
185+
}).listen(1337);
186+
```
187+
158188
## Constants
159189

160190
<!--type=misc-->
@@ -378,4 +408,5 @@ Decompress a Buffer or string with Unzip.
378408
[Inflate]: #zlib_class_zlib_inflate
379409
[InflateRaw]: #zlib_class_zlib_inflateraw
380410
[Unzip]: #zlib_class_zlib_unzip
411+
[`.flush()`]: #zlib_zlib_flush_kind_callback
381412
[Buffer]: buffer.html

0 commit comments

Comments
 (0)