javascript - NodeJS 中的动态分块响应

标签 javascript node.js httpresponse rxjs5 multipart

给定以下 JavaScript 伪代码(示例 1),
如您所见,有 3 个异步流依次写入响应。他们当然会以异步方式写入响应,因此不会保留 block 的顺序(实际上是不可预测的)。

import pre from './pre';
import content from './content';
import post from './post';

export function renderIndex(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/html; charset=utf-8',
    'Transfer-Encoding': 'chunked',
  });

  const onEnd = () => {
    if(!pre._readableState.ended) return;
    if(!body._readableState.ended) return;
    if(!post._readableState.ended) return;

    res.end();
  };

  pre.on('data', (chunk) => { res.write(chunk); }).on('end', onEnd);
  body.on('data', (chunk) => { res.write(chunk); }).on('end', onEnd);
  post.on('data', (chunk) => { res.write(chunk); }).on('end', onEnd);
}

是否可以告诉客户端每 block 数据的位置?

我想实现这样的目标:

// ---- Stream 1 keep open
<html>
  <head>
  ...
  ...
  ...
  ...


// --- Stream 2 keep open

<body>
  ...
  ...
  ...

// --- Stream 3 keep open
<script src="..."></script>
<script src="..."></script>
<script src="..."></script>


// --- Stream 1 CLOSE
  </head>

// --- Stream 2 CLOSE
  </body>

// --- Stream 3 CLOSE
  </html>


// res.end()
  1. Range Requests
  2. Multipart Range

类似大理石的解释:

  • 实际:[pre] [post] [body] [pre] [body] [/pre] [/post] [/body]
  • 所需 [pre] [/pre] [body] [/body] [post] [/post]

最佳答案

我相信您可以使用名为 highland.js 的库实现预期的行为。它为您提供了一种在流之上执行一些操作的方法

/*
the sample to show how it works
H([
  H([1, 2, 3]),
  H([4, 5, 6])
]).sequence().pipe(process.stdout);
*/

import pre from './pre';
import content from './content';
import post from './post';
const H = require('highland')

export function renderIndex(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/html; charset=utf-8',
    'Transfer-Encoding': 'chunked',
  });

  H([
    pre,
    content,
    post
  ]).sequence().pipe(res);
}

关于javascript - NodeJS 中的动态分块响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50502741/

相关文章:

json - 将对象从 MongoDB 游标流式传输到 Nodejs HTTP 响应

java - java中httpResponse返回null

javascript - focus方法触发按钮点击事件

javascript - 在 Vue.js 2.0 中将 css 类添加到 HTML 或 BODY 标记

angularjs - 加入现有的 Angular 应用以表达后端

javascript - 如何在不使用模板的情况下插入变量?

java - 为什么 HttpHead 比 HttpGet 返回时间更长

javascript - 执行位于另一个函数 Javascript 中的函数

Javascript 引用任意数字

ios - 如何使用 swift 创建聊天应用程序