Koa2-如何写入响应流? [英] Koa2 - How to write to response stream?
问题描述
使用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-stringified
- 无内容响应
ctx.body
只是ctx.response.body
因此,这里有一些示例,您将如何使用它(加上标准的koa主体分配)
So here are some examples how you could use it (plus standard koa body assignment)
通过调用服务器 -本地主机:8080/stream ...将以数据流响应 -本地主机:8080/file ...将以文件流响应 -本地主机:8080/...仅发送回标准正文
Calling the server with - localhost:8080/stream ... will respond with the data stream - localhost:8080/file ... will respond with the file stream - localhost:8080/ ... just sends back standard body
'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", "txt/html");
ctx.body = src;
} else {
// normal KOA response
ctx.body = 'BODY: Hello, World!' ;
}
});
app.listen(8080);
这篇关于Koa2-如何写入响应流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!