首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Koa:流式传输HTML

Koa:流式传输HTML
EN

Stack Overflow用户
提问于 2021-03-12 21:52:54
回答 1查看 132关注 0票数 0

使用Koa,我的一条路由有一个很长的过程,我想要流式传输正文以开始发送css和javascript,这样浏览器就可以在获得数据之前开始处理它( Google推荐)

这就是我在沙箱中尝试的方法:

代码语言:javascript
复制
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!

我想知道使用流是否可以实现我想要实现的目标?

EN

回答 1

Stack Overflow用户

发布于 2021-03-17 17:23:51

诀窍是需要设置ctx.type

代码语言:javascript
复制
'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)的

  • 标准响应从一个文件到另一个文件
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66601198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档