Create .csv and send as response in express/koa

Issue

I have some data in csv format and I want to send it as a file attachment (example.csv) to an http response without saving it as a temp file on the fs. Can this be done in express/koa?

Solution

If you have constructed a string of comma-separated values organized into lines separated by "\n", you can send it as an attachment with express middleware like the following:

app.get("/csvdownload", function(req, res) {
  var csv = "A,B\n1,2\n";
  res.set("Content-Disposition", "attachment; filename=whatever.csv");
  res.type("csv");
  res.end(csv);
});

Answered By – Heiko Theißen

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.