Skip to content

Instantly share code, notes, and snippets.

@killercup
Created January 21, 2014 10:58
Show Gist options
  • Save killercup/8538011 to your computer and use it in GitHub Desktop.
Save killercup/8538011 to your computer and use it in GitHub Desktop.
Stream data from Mongoose into CSV download
var Campaign = require('../model/campaign');
module.exports.getCampaignsCSV = function (req, res) {
function CSVEscape(field) {
return '"' + String(field || "").replace(/\"/g, '""') + '"';
}
var headers = [
'Code-Nummer', //num
'Kampagnenname', //name
'Kampagnenquelle', //source
'Kampagnenmedium', //medium
'Kampagnenbegriff', //term
'Kampagneninhalt' //content
].map(CSVEscape).join(',');
function docToCSV(doc) {
return [
doc.num,
doc.name,
doc.source,
doc.medium,
doc.term,
doc.content
].map(CSVEscape).join(',');
}
var started = false;
function start(response) {
response.setHeader('Content-disposition', 'attachment; filename=campaigns.csv');
response.contentType('csv');
response.write(headers + '\n');
started = true;
}
Campaign.find()
.sort('num')
.stream()
.on('data', function (campaign) {
if (!started) { start(res); }
res.write(docToCSV(campaign) + '\n');
})
.on('close', function () {
res.end();
})
.on('error', function (err) {
res.send(500, {err: err, msg: "Failed to get campaigns from db"});
});
};
@killercup
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment