Nodejs立即删除生成的文件

时间:2017-04-13 15:13:37

标签: node.js pdf dropbox fs unlink

我正试图在node.js中生成后立即删除pdf。生成的pdf作为电子邮件附件发送,上传到dropbox,然后从本地文件系统中删除。但是当我尝试删除它时,它不会删除它,也不会发送电子邮件。 pdf是使用html-pdf创建的。这是我的代码:

     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
 }

所以,当我执行fs.unlink' or fs.unlinkSync`时,如果文件已经存在,那么它可以工作,但是路径中生成的文件不会被删除。

1 个答案:

答案 0 :(得分:0)

NodeJs是异步的,因此您需要正确处理每个块。您的代码显示在完全创建PDF本身之前的某些时候,如果PDF创建速度很慢,将启动文件上传到Dropbox。

PDF文件的删除发生在邮件发送之前,所以你得到一些错误,但你没有在fs.unlink()中记录错误。将代码划分为块并使用回调以获得更好的性能和流量。

您的代码应该像这样正常工作..

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;
 //Generate the PDF first
 pdf.create(html, options).toFile(function(err, res) {
   if (err){
     return console.log(err);
   } else {
      //If success then read the PDF file and then upload to dropbox
     var dbx = new dropbox({ accessToken: mytoken });
     fs.readFile( path,function (err, contents) {
        if (err) {
          console.log('Error: ', err);
        } else {
          dbx.filesUpload({path: "/"+filename ,contents: contents }).then(function (response) {
            // Once the file upload is done then send mail
            console.log("done")
            sendMail('xyz', user.email, 'Confirmation received', filename, path, function(err, result){
              // once mail is successful then delete the file finally
              fs.unlinkSync(path); //if you need you can use callback with this for confirmation of deletion
            });
           }).catch(function(err) {
            console.log(err);
           });
        }
    });
   }
});

function sendMail(sender, receiver, subject, filename, path, callback){
  var mailOptions = {
    from: sender, // sender address
    to: receiver, // list of receivers
    subject: subject, // Subject line
    attachments : [{
      filename: filename,
      path : path
    }]
  };

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