简体   繁体   English

使用res.write压缩/ gzip /压缩流内容

[英]compress/gzip/deflate streaming content using res.write

var express = require('express')

var app = module.exports = express()

function getImages(callback) {
  callback()
}

app
.set('views', __dirname + '/views')
.set('view engine', 'jade')
.get('/stream/images', function(req, res) {
  res.render('layout', function(err, body) {
    res.type('html')
    res.write(body.replace('</body></html>', ''))
    getImages(function(err) {
      res.render('streams/images', function(err, body) {
        var html = '<div class="layout-stream">' + body + '</div>'
        res.write(
          "<script>$('.pagelet-layout-stream').replaceWith(" + 
          JSON.stringify(html) + 
          "); emitter.emit('check:stream');</script>"
        )
        res.write("<script>emitter.emit('load');</script>")
        res.write('</body></html>')
        res.end()
      })
    })
  })
})
.listen(3013)

This works exactly as intended. 这完全符合预期。 However, when I .use(express.compress()) (before .get to be exact), the page no longer streams. 然而,当我.use(express.compress()).get是精确的),该页面不再流。 In other words, the express.compress() seems to wait until the response is finished, then gzip the entire response, then send it. 换句话说, express.compress()似乎要等到响应完成后,再对整个响应进行gzip处理,然后再发送。 I would like each res.write to send a gzipped response (or specifically, every drain). 我希望每个res.write发送一个gzip压缩的响应(或具体来说,每个消耗)。 How can I compress the response correctly? 如何正确压缩响应?

Edit 1 - I tried this: 编辑1-我尝试过:

var stream = zlib.createGzip()
stream.pipe(res)

stream.write(/* stuff */)
stream.end()

This works exactly like express.compress() . 这与express.compress()完全一样。 I'm not sure whether the browser just doesn't parse the body until it has the whole thing, or it doesnt send the body until the response is complete. 我不确定浏览器是否只是在完整之前就解析了正文,还是在响应完成之前才发送正文。

var stream = zlib.createGzip()
stream._flush = zlib.Z_SYNC_FLUSH
stream.pipe(res)

stream.write(/* stuff */)
stream.end()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM