Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS JSON to CSV

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.

like image 891
Josh Brown Avatar asked Mar 14 '23 23:03

Josh Brown


1 Answers

You can use the following code snippet instead of the writeFile

res.attachment('file.csv');
res.send(csv)
like image 103
Julián Duque Avatar answered Mar 25 '23 00:03

Julián Duque