给定以下 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()
类似大理石的解释:
- 实际:
[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/