Flushing

在一个压缩流中调用 .flush() 会使得 zlib 尽可能多地返回当前的可能值。这可能会降低压缩质量的成本,但这在数据需要尽快使用时非常有用。

在以下的例子中,flush() 被用于在客户端写入一个部分压缩的 HTTP 响应:

  1. const zlib = require('zlib');
  2. const http = require('http');
  3. http.createServer((request, response) => {
  4. // For the sake of simplicity, the Accept-Encoding checks are omitted.
  5. response.writeHead(200, {
  6. 'content-encoding': 'gzip'
  7. });
  8. const output = zlib.createGzip();
  9. output.pipe(response);
  10. setInterval(() => {
  11. output.write(`The current time is ${Date()}\n`, () => {
  12. // The data has been passed to zlib, but the compression algorithm may
  13. // have decided to buffer the data for more efficient compression.
  14. // Calling .flush() will make the data available as soon as the client
  15. // is ready to receive it.
  16. output.flush();
  17. });
  18. }, 1000);
  19. }).listen(1337);