There are 20,000 records in mongodb collection. I am exporting all these records in a csv. I am send partial response using this :
res.writeHead(200, {
"Content-Type": "application/csv",
"Content-disposition": "attachment; filename='import.csv'"
});
res.write(data + '0', "binary");
Above code is executing in batch of 500. I am ending using this code when all records are processed.
if (++responseCount == loopCount) {
res.end();
}
But I got this error :
Can't set headers after they are sent.
But I get the file downloaded with 500 records.
Here is my full code.
var exportData = function (req, res, next) {
var limit = 500;
var responseCount = 0;
var loopCount = 1;
var size = 30000;
//Get 500 records at one time
var getData = function (req, start, cb) {
req.db.collection('items').find().skip(start).limit(limit).toArray(function (err, records) {
if (err) throw err;
cb(null, records);
});
};
if (size > limit) {
loopCount = parseInt(req.size / limit);
if ((req.size % limit) != 0) {
loopCount += 1;
}
}
for (var j = 0; j < loopCount; j++) {
getData(req, limit * j, function (err, records) {
if (err) throw err;
records.forEach(function (record) {
//Process record one by one
});
res.write(records);
if (++responseCount == loopCount) {
res.setHeader('Content-type', 'application/csv');
res.setHeader("Content-disposition", 'attachment; filename="import.csv"');
res.end();
}
});
}
};