node.js实现BigPipe详解

2020-06-17 05:42:37易采站长站整理

  –n || res.end()
})

s2 的处理与此类似。这时你会看到,请求网页的第二秒,出现两个空白虚线框,第五秒,出现 Partial 2 部分,第八秒,出现 Partial 1 部分,网页请求完成。

至此,我们就完成了一个最简单的 BigPipe 技术实现的网页。

需要注意的是,要写入的网页片段有 script 标签的情况,如将 s1.jade 改为:


h1 Partial 1
.content!=content
script
  alert(“alert from s1.jade”)

然后刷新网页,会发现这句 alert 没有执行,而且网页会有错误。查看源代码,知道是因为 <script> 里面的字符串出现 </script> 而导致的错误,只要将其替换为 </script> 即可

res.write(‘<script>$(“#s1”).html(“‘ + temp.s1(s1data).replace(/”/g, ‘”‘).replace(/</script>/g, ‘</script>’) + ‘”)</script>’)

以上我们便说明了 BigPipe 的原理和用 node.js 实现 BigPipe 的基本方法。而在实际中应该怎样运用呢?下面提供一个简单的方法,仅供抛砖引玉,代码如下:


var resProto = require(‘express/lib/response’)
resProto.pipe = function (selector, html, replace) {
  this.write(‘<script>’ + ‘$(“‘ + selector + ‘”).’ +
    (replace === true ? ‘replaceWith’ : ‘html’) +
    ‘(“‘ + html.replace(/”/g, ‘”‘).replace(/</script>/g, ‘</script>’) +
    ‘”)</script>’)
}
function PipeName (res, name) {
  res.pipeCount = res.pipeCount || 0
  res.pipeMap = res.pipeMap || {}
  if (res.pipeMap[name]) return
  res.pipeCount++
  res.pipeMap[name] = this.id = [‘pipe’, Math.random().toString().substring(2), (new Date()).valueOf()].join(‘_’)
  this.res = res
  this.name = name
}
resProto.pipeName = function (name) {
  return new PipeName(this, name)
}
resProto.pipeLayout = function (view, options) {
  var res = this
  Object.keys(options).forEach(function (key) {
    if (options[key] instanceof PipeName) options[key] = ‘<span id=”‘ + options[key].id + ‘”></span>’
  })
  res.render(view, options, function (err, str) {
    if (err) return res.req.next(err)
    res.setHeader(‘content-type’, ‘text/html; charset=utf-8’)
    res.write(str)
    if (!res.pipeCount) res.end()
  })
}
resProto.pipePartial = function (name, view, options) {