简体   繁体   English

koa-write 是做什么的?

[英]What does koa-write do?

My project uses the Koa framework, and I'm looking for a way to replace Express's res.write to stream large datasets into a csv.我的项目使用 Koa 框架,我正在寻找一种方法将 Express 的 res.write 替换为 stream 大型数据集到 csv。

Can I use koa-write to do this?我可以使用koa-write来做到这一点吗? Something like:就像是:

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");
});

I tried it but it doesn't seem to work.我试过了,但它似乎不起作用。

you can just create a Readable stream and assign to ctx.body你可以创建一个可读的 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);

Or if you already have a stream, just assign to body.或者,如果您已经拥有 stream,只需分配给 body。 otherwise, create a new Stream and push data to it.否则,创建一个新的 Stream 并将数据推送到它。 Terminate the stream with null用 null 终止null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM