0

I am trying to export a csv file (pulling the data from mongodb). My frontend is ionic (angular) and backend is Azure function (nodejs), I want the frontend to be able to download this csv file.

My code:

const { db, connection } = await createMongoClient();
const collection = db.collection("dummy");

try {
    const data = await collection.find({}).toArray();
    connection.close();

    const ws = fs.createWriteStream(Date.now() + ".csv");

    fastcsv
        .write(data, { headers: true })
        .on("finish", function () {
        console.log("Write CSV successfully!");
        })
        .pipe(ws);

    res.status(201).json({ success: true });
} catch (err) {
    res.status(500).json({ err, success: false });
}

The above creates a csv file but its not downloaded by the frontend.

Exhaler
  • 105
  • 1
  • 9

1 Answers1

0

Firstly, add

 res.status(201).json({ success: true }); --- remove this line
 res.status(200).send(file being created as csv);

On Frontend in your service create a download method that requests the file on user click;

this.http.get('REST end point', { responseType: 'blob'}).subscribe(res => {
     window.open(window.URL.createObjectURL(res));
   });

check if this works!

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
  • I tried this ```res.send(ws);``` but i didn't get the csv file only text, which wasn't the csv data – Exhaler Jan 09 '21 at 17:33
  • you can use express-csv module. It can help you sending your response in csv form or you can get the JSON data from backend to frontend(if your data is not really big), and use module from JSON-to-CSV, I am attaching a link - https://medium.com/mycoding/export-json-to-csv-file-in-angular-d1b674ec79ed . It can help you implement how to use it. – Apoorva Chikara Jan 09 '21 at 17:44