Created
January 21, 2014 10:58
-
-
Save killercup/8538011 to your computer and use it in GitHub Desktop.
Stream data from Mongoose into CSV download
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Newer code: https://gist.github.com/killercup/11256050