0

Right now Im working with Node JS using PDFKit to generate PDF files, I want to delete the file after sent it by email using Nodemailer, here is my code:

reportcontroller.sendrecordsemail = async (req,res)=>{
    try{
        const doc = new PDF({
            bufferPages: true,
            compress: false,
            margins: {top: 20, left: 10, right: 10, bottom: 20}});
             
        const filename = `Report-${datehelper.dateformatlarge(Date.now())}.pdf`;
        const stream = res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': `attachment; filename=${filename}`
        });
        const records = await queryaux.showrecords();
        let count = 1;
        const arecords = records[0].map((record) =>{
            arecord ={
                Name: record.Name,
                RecordType: record.RecordType,
                RecordDate: datehelper.dateformatshort(record.RecordDate),
                EntryTime: record.EntryTime,
                ExitTime: record.ExitTime,
                TotalHours: record.TotalHours
            }
            count++;
            return arecord;
        })
        doc.setDocumentHeader({...
        })
        doc.addTable([...
        })
        doc.render();
        const writestream = fs.createWriteStream(`Node/src/download/${filename}`);
        doc.pipe(writestream);
        const transporter = nodemailer.createTransport({
            host: "smtp.gmail.com",
            port: 465,
            secure: true,
            auth: {
              user: '-----',
              pass: '-----', 
            },
        });
        const mailOptions = {
            from: "----",
            to:"----",
            subject:"Test",
            text:"Test",
            attachments:[
                {
                    filename: `${filename}`,
                    path:`Node/src/download/${filename}`
                }
            ]
        }
        transporter.sendMail(mailOptions, (error, info) => {
            if(error){
                res.status(500).send({Error: error})
            }
            else{
                console.log('Mail sent successfully!');
            }
        });
        doc.on('data',(data)=>{stream.write(data)});
        doc.on('end',()=>{stream.end()});
        doc.end();
        fs.unlink(`Node/src/download/${filename}`,function(err){
            if(err){
                throw err;
            }else{
                console.log('Successfully deleted the file');
            }
        })
    }
    catch(error){
        console.log({Error: error})
    }
}

This is what I got on console:

Successfully deleted the file
Mail sent successfully!

When I check my email the file is right there so Nodemailer is working, however, even though I deleted the file using fs.unlink() the file is still in the folder. If I request the petition again i got the next error:

Error: ENOENT: no such file or directory, open 'Node/src/download/Report.pdf'

Does anyone know what I am doing wrong or any way I can fix it?

I would appreciate it very much, thank you.

2 Answers2

0

You can delete pdf file after document process done.

doc.on('end', () => {
  fs.unlink(filePath, err => {
    next(err)
  });
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

Create separate function to send email which will take callback function as parameter and when your sendMail() {which is a function of nodemailer package in javascript function will return you can call your own callback to delete file you will get better idea with picture below:

In this image you can took how to declare custom sendMail function with callback parameter:

And this is how you can call it:

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Juffler
  • 1
  • 1
  • 1
    Please post your code directly to the answer, no need of adding extra URLs that can become invalid in future. – Tyler2P Dec 21 '22 at 18:23