0

In this question several ways were proposed to parse a json array into csv.

However in the answers given, fs is used to write the csv too. I am wondering whether it is possible to just convert a csv and make it available for the client to download without having to write it somewhere in the server? After all, the json already exists and writing a csv seems like duplication.

In my case I have a server with a mongodb collection which I'd like to make available portions of to clients as a csv.

thank you for your help!

Community
  • 1
  • 1
qts
  • 984
  • 2
  • 14
  • 25
  • Sure there is, just output the csv in `res.send` with a Content-Disposition header set to `"attachment;filename=myfilename.csv"`, and it downloads – adeneo Jan 10 '16 at 14:10

1 Answers1

0

You can convert the JSON to csv with client side javascript like in the question you linked. Then you can make the browser download that file as a csv as described here

So like this:

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

var json = getYourJSONObject();
var csv = convertJSONToCsv(json);

var name = "filename";
download(name+".csv",csv);

Hope this help :)

Community
  • 1
  • 1
Rosh
  • 53
  • 1
  • 5