![](/img/trans.png)
[英]koa js: What does “next” refer to, and can cascading be implemented differently?
[英]What does koa-write do?
我的項目使用 Koa 框架,我正在尋找一種方法將 Express 的 res.write 替換為 stream 大型數據集到 csv。
我可以使用koa-write來做到這一點嗎? 就像是:
var write = require('koa-write');
router.get('/', (ctx, next) => {
ctx.response.set('Content-Type', 'text/csv');
ctx.response.set('Content-Disposition', 'attachment; filename=data.csv');
write(ctx, "1,2,3,4,5\n");
});
我試過了,但它似乎不起作用。
你可以創建一個可讀的 stream 並分配給ctx.body
const Koa = require("koa");
const { Readable } = require("stream");
const app = new Koa();
const s = new Readable();
app.use((ctx) => {
if (ctx.request.url === "/") {
ctx.body = s;
s.push('"1,2,3,4,5\n');
s.push("test test");
s.push(null); // indicates end of the stream
} else {
ctx.throw(404);
}
});
app.listen(8080);
或者,如果您已經擁有 stream,只需分配給 body。 否則,創建一個新的 Stream 並將數據推送到它。 用 null 終止null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.