use*_*467 4 javascript stream node.js koa2
使用Koa2,我不确定如何将数据写入响应流,因此在Express中,它类似于:
res.write('some string');
Run Code Online (Sandbox Code Playgroud)
我知道我可以将流分配给它,ctx.body但是我对node.js流太不熟悉,所以不知道如何创建该流。
koa文档可让您为响应分配流:(来自https://koajs.com/#response)
ctx.response.body =
将响应主体设置为以下之一:
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", "txt/html");
ctx.body = src;
} else {
// normal KOA response
ctx.body = 'BODY: Hello, World!' ;
}
});
app.listen(8080);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4282 次 |
| 最近记录: |