本文介绍了Koa2 - 如何写入响应流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Koa2,但我不确定如何将数据写入响应流,因此在 Express 中它会类似于:

Using Koa2 and I'm not sure how to write data to the response stream, so in Express it would be something like:

res.write('some string');

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

I understand that I can assign a stream to ctx.body but I'm not familiar with node.js streams too well so don't know how I would go about creating this stream.

推荐答案

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

The koa documentation allows you to assign a stream to your response: (from https://koajs.com/#response)

ctx.response.body=

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

Set response body to one of the following:

  • 写入的字符串
  • 缓冲区写入
  • 流管道
  • 对象 ||数组 json 字符串化
  • null 无内容响应

ctx.body 只是 ctx.response.body

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

So here are some examples how you could use it (plus standard koa body assignment)

调用服务器

  • 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);

这篇关于Koa2 - 如何写入响应流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 16:40