I have this ExpressJS code that I am working with. My application sends an array of _id's which I search for and grab from mongo. I am then trying to generate a CSV of the data returned. The code below is working as expected. It is writing the CSV to the root directory of my application. The modification I am wanting to make is that I want the file to download to the users machine. I have been googling this topic for quite some time now and everyone says that in order to download a file you need to use fs.createWriteStream
or res.download()
however I dont know how to implement it with my current method structure. Obviously it needs to happen inside json2csv()
after the csv is created. Id rather not have to write the file, stream, then delete. Id like it if I could just stream.
The json2csv package I am using is here: https://www.npmjs.com/package/json2csv
router.post('/Equipment/Report', function(req, res, next) {
var filteredData = req.body;
console.log(filteredData);
Equipment.find({_id: { $in: filteredData }}, function(err, Equipment) {
console.log(Equipment);
var fields = ['ClassPrefix', 'UnitNumber'];
json2csv({ data: Equipment, fields: fields}, function(err, csv) {
if (err) console.log(err);
fs.writeFile('file.csv', csv, function(err) {
if (err) throw err;
console.log('file saved');
});
});
});
//console.log(filteredData);
});
EDIT to suggested code -
router.post('/Equipment/Report', function(req, res, next) {
var filteredData = req.body;
console.log(filteredData);
Equipment.find({_id: { $in: filteredData }}, function(err, Equipment) {
console.log(Equipment);
var fields = ['ClassPrefix', 'UnitNumber'];
json2csv({ data: Equipment, fields: fields}, function(err, csv) {
if (err) console.log(err);
console.log(csv);
res.attachment('data.csv');
res.send(csv);
});
});
});
This does not download any file. Logs a response of 200.
You can use the following code snippet instead of the writeFile
res.attachment('file.csv');
res.send(csv)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With