0

I am creating a REST API that will allow the user to download a file when the API is called, the file is getting downloaded but additionally I need to send a a response back using res.json({status : true}) after file is downloaded successfully and deleted from the file system.

I have tried many different ways like using the request module, creating my own middleware, but nothing works. Either file does not get downloaded and response is sent or response is not sent but file is downloaded.

Please find the API code below:

    router.route('/generatePdf')
        .get((req, res, next) => {
            res.json({
                status: false,
                message: "Invalid Request made"
            })
        })

        .post((req, res, next) => {
            try{
                let id = req.body.id;
                console.log(id + " :this is id"); //I get the mongo ID here
                if(id != null && id != ''){
                    if(validator.isMongoId(id)){
                        //fetch the data and generate the pdf
                        myFunctions.fetchInfoById(id, (err, user) => {
                            if (err) {
                                console.log('Err in fetchInfoById '+err);
                                res.json({
                                    status: false
                                })
                            } else if (user!= null && user!= '') {
                              res.render('./referral/referralPdf/PdfTemplate.ejs', {
                                    user: user
                            }, (err, html) => {
                                    if (err) {
                                        console.log('Err in rendering PDFTemplate ' + err);
                                        res.json({
                                            status: false
                                        })
                                    } else {
                                        let options = {
                                            format: 'A4', // allowed units: A3, A4, A5, Legal, Letter, Tabloid
                                            orientation: 'portrait',
                                            timeout: '100000',
                                            zoomFactor: 0.7
                                        }
                                        pdf.create(html, options).toFile('./public/pdf/' + 'report.pdf', (err, response) => {
                                            if (err) {
                                                console.log('Error in generating pdf' + err);
                                                res.json({
                                                    status: false
                                                })
                                            } else {
                                                res.download(response.filename, 'fileContent.pdf', (err) => {
                                                    if (err) {
                                                        console.log(err);

                                                    } else {
                                                        fs.unlink(response.filename, (err) => {
                                                            if (err) {
                                                               console.log(err);
                                                               //send response as
                                                               res.json({
                                                                 status : false
                                                               })
                                                              }else{
                                                                console.log('FILE REMOVED!');
                                                                res.json({
                                                                    status : true
                                                                })
                                                              }
                                                            });
                                                        }
                                                    })
                                                }
                                            })
                                        }
                                    })
                                } else {
                                    res.json({
                                        status: false
                                    })
                                }
                            })
                        } else {
                            res.json({
                                status: false
                            })
                        }
                    } else {
                        res.json({
                            status: false
                        })
                    }
                } catch(e){
                    console.log("catch " + e);
                    res.json({
                        status: false
                    })
                }
            })

Please help me with a way of achieving this, I have been at it for hours but could not come up with a better solution. P.S: with the code above I get error can't set headers after they are sent to the client

The issue I am facing is sending a response back to client once the download is successful and file is deleted from the file system. I am able to use res.render() followed by res.download(). but I am not able to use res.json({status : success}) after download.

hushie
  • 417
  • 10
  • 23
  • 1
    Possible duplicate of [Node JS : Error with res.download() after res.render()](https://stackoverflow.com/questions/47057761/node-js-error-with-res-download-after-res-render) – eol Apr 02 '19 at 07:58
  • @eol the issue I have is similar to the one you pointed. But in my case if I have to do a get request also, I still need to send the filename of the file generated in my post request, I have tried this as well but it did not work. – hushie Apr 02 '19 at 08:25

0 Answers0