【问题标题】:Nodejs Immediately delete generated fileNodejs 立即删除生成的文件
【发布时间】:2017-09-09 19:04:51
【问题描述】:

我正在尝试在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' orfs.unlinkSync` 时,如果文件已经存在,它可以工作,但路径中生成的文件不会被删除。

【问题讨论】:

  • 您需要等到您发送完电子邮件。
  • console.log 是你最好的朋友,如果你打印一些东西而不是 unlinkSync(path),你会注意到你的 Message sent [...] 在你尝试删除文件之后出现

标签: node.js pdf dropbox fs unlink


【解决方案1】:

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

并且 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)
     }
  });
}
}

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 2015-08-20
    • 2017-05-03
    • 2014-01-07
    • 1970-01-01
    相关资源
    最近更新 更多