Sunday, 18 August 2013

How to export csv nodejs

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 save part but, it does not work
correctly and I get the content error and what not, not sure if that has
to do because it is not in the app.js aka main file)
exports.downloadContacts = function(req, res) {
async.waterfall([
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 = friends.map(function (user) {
userMap[user.friend_id] = user;
return user.friend_id;
});
console.log(friends);
User.find({_id: {$in: friendIds}}, function(err, users) {
if(err) {console.log(err);
} else {
for(var i = 0; i < users.length; i++) {
console.log('users')
//console.log(users[i]);
source.push(users[i].firstNameTrue,
users[i].lastNameTrue, users[i].emailTrue,
users[i].phone, users[i].emailList,
users[i].phoneList)
}
console.log(source);
callback(null, source);
}
});
}
});
}
],
function(err, source) {
var result = [];
res.content('csv');
csv()
.from(source)
.on('data', function(data){
result.push(data.join());
})
.on('end', function(){
res.send(result.join('\n'));
});
});
};

No comments:

Post a Comment