Lion789 Lion789 - 1 year ago 154
Node.js Question

How to export csv nodejs

Hey I am trying to export a csv from node.js (pulling the data from mongodb). I already have the data being pulled and separated by commas and all, but now I am trying to figure out how to actually send it... I am sticking this code in my routes file. Any advice on how to take the array of data and send it to a user straight for download on request.

here is the code: (I attempted the the bottom part of the code the second function)

exports.downloadContacts = function(req, res) {
function(callback) {
var source = [];
Friend.find({userId: req.signedCookies.userid}, function(err, friends) {
if(err) {console.log('err with friends for download');
} else {
var userMap = {};
var friendIds = (user) {
userMap[user.friend_id] = user;
return user.friend_id;
User.find({_id: {$in: friendIds}}, function(err, users) {
if(err) {console.log(err);
} else {
for(var i = 0; i < users.length; i++) {
source.push(users[i].firstNameTrue, users[i].lastNameTrue, users[i].emailTrue, users[i].phone, users[i].emailList, users[i].phoneList)
callback(null, source);



function(err, source) {
var result = [];


.on('data', function(data){
.on('end', function(){

Answer Source

Have you tried something like this with a content type as "application/octet-stream"

res.set('Content-Type', 'application/octet-stream');
res.send(<your data>);

or simply

res.send(new Buffer(<your data>));

Express send() docs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download