i have written a API to export User collection to CSV , from MONGODB . the API is called on a button click and it export the data into CSV ... now the problem is that when this API is called it generates the RESULT FILE IN MY PROJECT , i want the result file to get Download on client side , means when user click on EXPORT button it show a SAVE AS option , USER select the fOLDER , NAME etc and then the file get downloaded on CLIENT COMPUTER ... any idea how to acheive this ... I,M using NODE JS , MONGODB and JSON2CSV module for data conversion ... below is my code
app.get('/USER/exporttocsv', function (req, res, next) {
USER.find().select('-__v').lean().exec({}, function (err, products) {
const json2csvParser = new Json2csvParser({ header: true });
const csvData = json2csvParser.parse(products);
fs.writeFile("bezkoder_mongodb_fs.csv", csvData, function (error) {
if (error) throw error;
console.log("Write to bezkoder_mongodb_fs.csv successfully!");
});
});
})
Add the response.download() method to your code. This will enable the user to download the file on the client-side:
res.download('path/to/file-to-download');