在压缩流上调用 [.flush()] 方法将使 zlib 返回尽可能多的输出。 这可能是以压缩质量下降为代价的,但是当需要尽快提供数据时,这可能是有用的。

    在以下的实例中, flush() 方法用于将部分压缩过的 HTTP 响应返回给客户端:

    1. const zlib = require('zlib');
    2. const http = require('http');
    3. const { pipeline } = require('stream');
    4. http.createServer((request, response) => {
    5. // 为了简单起见,省略了对 Accept-Encoding 的检测。
    6. response.writeHead(200, { 'content-encoding': 'gzip' });
    7. const output = zlib.createGzip();
    8. let i;
    9. pipeline(output, response, (err) => {
    10. if (err) {
    11. // 如果发生错误,则我们将会无能为力,
    12. // 因为服务器已经发送了 200 响应码,
    13. // 并且已经向客户端发送了一些数据。
    14. // 我们能做的最好就是立即终止响应并记录错误。
    15. clearInterval(i);
    16. response.end();
    17. console.error('发生错误:', err);
    18. }
    19. });
    20. i = setInterval(() => {
    21. output.write(`The current time is ${Date()}\n`, () => {
    22. // 数据已经传递给了 zlib,但压缩算法看能已经决定缓存数据以便得到更高的压缩效率。
    23. // 一旦客户端准备接收数据,调用 .flush() 将会使数据可用。
    24. output.flush();
    25. });
    26. }, 1000);
    27. }).listen(1337);