Download csv file node.js

前端 未结 2 1130
北海茫月
北海茫月 2021-02-19 20:07

I am building an app using node.js and trying to download data as a csv file. I am using json2csv (https://www.npmjs.com/package/json2csv) for this purpose. However, the way I h

相关标签:
2条回答
  • 2021-02-19 20:34

    Use res.send if you use express.

    You have to define a HTTP GET route which looks something like that:

    app.get("/pathToYourDownload", function (req, res) {
      json2csv({ data: myCars, fields: fields }, function(err, csv) {
        res.setHeader('Content-disposition', 'attachment; filename=data.csv');
        res.set('Content-Type', 'text/csv');
        res.status(200).send(csv);
      });
    });
    
    0 讨论(0)
  • 2021-02-19 20:55

    On express server:

    const json2csv = require('json2csv').parse;
    
    const csvString = json2csv(yourDataAsArrayOfObjects);
    res.setHeader('Content-disposition', 'attachment; filename=shifts-report.csv');
    res.set('Content-Type', 'text/csv');
    res.status(200).send(csvString);
    

    On client (otherwise most of the browsers will not download the file, even you will see the proper response in the network panel):

    window.open(downloadUrl);
    
    0 讨论(0)
提交回复
热议问题