【问题标题】:Koa: Stream the HTMLKoa:流式传输 HTML
【发布时间】:2021-06-10 13:08:38
【问题描述】:

使用 Koa,我的一条路线有一个漫长的过程,我想流式传输正文以开始发送 css 和 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! 的文件。

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

【问题讨论】:

    标签: node.js koa nodejs-stream koa2


    【解决方案1】:

    诀窍是需要设置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);
    

    这个例子显示

    • 标准回复 (localhost:8080/)
    • 文件之间的流 (localhost:8080/file)
    • 从可读流到 html (localhost:8080/stream) 的流

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 2021-03-13
      • 1970-01-01
      • 2011-03-08
      相关资源
      最近更新 更多