Thursday, 13 April 2017

Nodejs Immediately delete generated file

I'm trying to delete a pdf immediately after is has been generated in node.js. The generated pdf is sent as an email attachment, uploaded to dropbox and then deleted from the local file system. But as i try to delete it , it does not delete it and it does not send the email either. The pdf is created using html-pdf. Here is my code :

     if (result) {
       var filename = user.number+ ".pdf";
       var path = './public/files/'+filename ;
       var options = { filename: path, format: 'Legal', orientation: 'portrait', directory: './public/files/',type: "pdf" };
       html = result;
       pdf.create(html, options).toFile(function(err, res) {
      if (err) return console.log(err);
      console.log(res);
      });
     var dbx = new dropbox({ accessToken: mytoken });
     fs.readFile( path,function (err, contents) {
            if (err) {
                   console.log('Error: ', err);
            }
            dbx.filesUpload({ path: "/"+filename ,contents: contents })
                           .then(function (response) {
                            console.log("done")
                            console.log(response);
                           })
                            .catch(function (err) {
                             console.log(err);
                             });
                            });

            var mailOptions = {
            from: 'xyz', // sender address
            to: user.email, // list of receivers
            subject: 'Confirmation received', // Subject line
            attachments : [{
                            filename: filename,
                            path : path                                                                           
                           }]
                     };

            transporter.sendMail(mailOptions, (error, info) => {
                if (error) {
                               return console.log(error);
                           }
                                 console.log('Message %s sent: %s', info.messageId, info.response);

                               });
             fs.unlinkSync(path); // even tried fs.unlink , does not delete file
            // fs.unlinkSync(someother file); this one works
 }

So when i do fs.unlink' orfs.unlinkSync`, if the file is already there it works but the files that is generated as in path doesn't get deleted.



via scrpaingnoob

No comments:

Post a Comment