使用Koa,我的一条路由有一个很长的过程,我想要流式传输正文以开始发送css和javascript,这样浏览器就可以在获得数据之前开始处理它( Google推荐)
这就是我在沙箱中尝试的方法:
const app = new koa();
const readable = require("stream").Readable;
const s = new readable({ read(size) {} });
app.use(async (ctx, next) => {
ctx.response.set("content-type", "txt/html");
s.push("Hello, World!");
ctx.body = s;
});
app.listen(8080);当我访问该站点时,我的浏览器会下载一个包含Hello, World!的文件,而不是看到文本Hello, World!。
我想知道使用流是否可以实现我想要实现的目标?
发布于 2021-03-17 17:23:51
诀窍是需要设置ctx.type:
'use strict';
const koa = require('koa');
const fs = require('fs');
const app = new koa();
// response
app.use(ctx => {
if (ctx.request.url === '/stream') {
const readable = require('stream').Readable
const s = new readable({ read() { } });
// stream data
ctx.response.set("content-type", "txt/html");
ctx.type = 'html'; // <-- THIS is the important step!
s.push('STREAM: Hello, World!');
s.push(null); // indicates end of the stream
ctx.body = s;
} else if (ctx.request.url === '/file') {
// stream file
const src = fs.createReadStream('./big.file');
ctx.response.set("content-type", "txt/html");
ctx.body = src;
} else {
// normal KOA response
ctx.body = 'BODY: Hello, World!';
}
});
app.listen(8080);此示例显示了
从可读流到html (localhost:8080/stream)的
https://stackoverflow.com/questions/66601198
复制相似问题