【问题标题】:Koa2 - How to write to response stream?Koa2 - 如何写入响应流?
【发布时间】:2018-07-28 11:44:23
【问题描述】:

使用 Koa2,我不知道如何将数据写入响应流,所以在 Express 中会是这样的:

res.write('some string');

我知道我可以为 ctx.body 分配一个流,但我对 node.js 流不太熟悉,所以不知道如何创建这个流。

【问题讨论】:

    标签: javascript node.js stream koa2


    【解决方案1】:

    koa 文档允许您为响应分配一个流:(来自https://koajs.com/#response

    ctx.response.body=

    将响应正文设置为以下之一:

    • 字符串写入
    • 缓冲区写入
    • 流式传输
    • 对象 ||数组 json-stringified
    • null 无内容响应

    ctx.body 只是ctx.response.body 的快捷方式

    这里有一些你可以如何使用它的例子(加上标准的 koa 身体分配)

    调用服务器

    • localhost:8080/stream ... 将响应数据流
    • localhost:8080/file ... 将响应文件流
    • localhost:8080/ ... 只是发回标准正文
    'use strict';
    const koa = require('koa');
    const fs = require('fs');
    
    const app = new koa();
    
    const readable = require('stream').Readable
    const s = new readable;
    
    // response
    app.use(ctx => {
        if (ctx.request.url === '/stream') {
            // stream data
            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", "text/html");
            ctx.body = src;
        } else {
            // normal KOA response
            ctx.body = 'BODY: Hello, World!' ;
        }
    });
    
    app.listen(8080);
    

    【讨论】:

    • @AbhishekAnand 现在再次对其进行了测试......工作正常。如果您使用 localhost:8080/file 调用服务器,当然您需要确保您的应用程序目录中有一个文件(在此示例中名为“big.file”)。如果您有问题,请更具体并提供您收到的错误消息。
    • 它说“_read() 未在可读流上实现”。用 new readable({ read(size) { } }); 修复了它
    • 正确的 HTML 内容类型是 text/html,而不是 txt/html
    • @NinaLisitsinskaya 是的,你完全正确!我在原帖中更正了。谢谢!
    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多