'How to download a generated csv file from backend in the client side

I am using ejs and node. On a button press there I am generating a csv file containing some information. I want to download that in the client side. This is the code I am trying but its not working.

app.post('/', async(req, res) => {

console.log('triggerd');
console.log('req', req.body);
const url= req.body.url;
await scrapeData(url);
const file = `${__dirname}/companies1.csv`;
res.download(file); // Set disposition and send it.
res.redirect('/')

})

Please help if possible.



Solution 1:[1]

Firstly, if you want to retrieve data from your backend, you should use a get request and not a post request. Post requests are for sending data from front to back, and get requests for sending data from back to end.

Secondly, if you want to send a file from your node.js server, you can use the following method :

const fs = require('fs');
fs.readFile(pathToYourFile, async (error: Error, data: any) => {
                    if (error) return console.log(error);
                    res.write(data, 'binary');
                    res.status(200).end(null, 'binary');
                });

This will return a binary value of your file, that you will have to convert to a string and then to a file, using a function such as this (this one is in angular/typescript, I don't really know if it applies to ejs) :

this.http.get(yourURL, {headers: this.headers, responseType: 'arraybuffer'})
      .subscribe( (result: any) => {
        let binary = '';
        const bytes = new Uint8Array( result );
        const len = bytes.byteLength;
        for (let i = 0; i < len; i++) {
          binary += String.fromCharCode( bytes[ i ] );
        }
        this.image = 'data:text/csv;base64,' + btoa(binary);
      });

With this solution, you can use the csv file in your front code, but it is not saved in the client's computer

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 liguepk