【问题标题】:How to stream a file without saving it down first?如何在不先保存文件的情况下流式传输文件?
【发布时间】:2021-05-18 13:34:04
【问题描述】:

我将以下代码放在一起,使用 json2csv 库创建名为 example.csv 的 CSV。

我希望不必在将 CSV 文件传递​​到前端进行下载之前保存和存储它。

如果不先保存文件,我似乎无法弄清楚如何将文件流式传输或通过管道传输到前端。

如何获取json2csv库的输出CSV文件并直接发送到前端?

我的一些代码

    const input = new Readable({ objectMode: true });
    input._read = () => {};
    input.push(JSON.stringify(parsed));
    input.push(null);

    var outputPath = "example.csv";
    const output = createWriteStream(outputPath, { encoding: "utf8" });
    const json2csv = new Transform(opts, transformOpts);

    // Pipe to output path
    input.pipe(json2csv).pipe(output);
    
    res.setHeader("Content-Type", "text/csv");
    res.download(outputPath);

【问题讨论】:

    标签: node.js express json2csv


    【解决方案1】:

    您可以简单地将json2csv 流通过管道传递给res 对象,例如:

    const ReadableStream = require('stream').Readable;
    
    app.get('/csv', (req, res) => {
        const stream = new ReadableStream();
        stream.push(JSON.stringify(data));
        stream.push(null);
    
        const json2csv = new Json2csvTransform({}, transformOpts);
        res.setHeader('Content-disposition', 'attachment; filename=data.csv');
        res.writeHead(200, { 'Content-Type': 'text/csv' });
        stream.pipe(json2csv).pipe(res);
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      相关资源
      最近更新 更多