Creating a CSV file from the Meteor.js collection

I have written my code so far and can get a list of all the entries to show on the web page, but I need to be able to get it as a CSV file (comma separated values).

The page currently displays a list, for example:

Name Address Description Bob 1 street Journalist Bill 2 street Fireman etc... 

Anyway, can I create a meteorite CSV file for download and not display it as a web page with all the HTML markup?

+5
source share
1 answer

Based How to serve a file using an iron router or the meteor itself?

HTML:

 <template name="blah"> <a href="{{pathFor 'csv'}}">Download the CSV</a> </template> 

JS:

 // An example collection var DummyData = new Mongo.Collection("dummyData"); // create some sample data if (Meteor.isServer) { Meteor.startup(function() { var dummyDataCursor = DummyData.find(); if (dummyDataCursor.count() === 0) { for(var i=1; i<=100; i++) { DummyData.insert({Name: "Name" + i,Address: "Address" + i, Description:"Description" + i}); } } }); } Router.route('/csv', { where: 'server', action: function () { var filename = 'meteor_dummydata.csv'; var fileData = ""; var headers = { 'Content-type': 'text/csv', 'Content-Disposition': "attachment; filename=" + filename }; var records = DummyData.find(); // build a CSV string. Oversimplified. You'd have to escape quotes and commas. records.forEach(function(rec) { fileData += rec.Name + "," + rec.Address + "," + rec.Description + "\r\n"; }); this.response.writeHead(200, headers); return this.response.end(fileData); } }); 
+7
source

Source: https://habr.com/ru/post/1208086/


All Articles