Synchronous function to check files in Nodejs?

Asked

Viewed 524 times

0

I am creating PDF’s on my Nodejs server using the Express framework and the Pdfmake library. If anyone looks at my profile they will see that I asked a question about corrupted PDF after downloading. It turns out that I have discovered that the files are corrupted because they are sent for download even before their creation is completed as the whole process occurs asynchronously. What I need to know is the following: With which SYNCHRONOUS process I could check whether the file is ready and can be sent for download, or how do I create the PDF synchronously??

Server:

pdfMake = printer.createPdfKitDocument(docDefinition);
pdfMake.pipe(fs.createWriteStream('../pdfs/Tabela.pdf'));
console.log('Imprimiu!!');
pdfMake.end();
if(fs.existsSync('C:/ProjetosLeonardo/Relatorios/pdfs/Tabela.pdf')) {
    let file = 'C:/ProjetosLeonardo/Relatorios/pdfs/Tabela.pdf';
    res.download(file);
}

Client:

 axios({
      method: 'post',
      url: '/server/gerarpdf',
      responseType: 'arraybuffer',
      data: this.pessoas
    })
    .then(function (response) {
      let blob = new Blob([response.data], {type: 'application/pdf'})
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'TabelaTeste.pdf'
      link.click()
    })
  • Share relevant code snippet from file creation and download please.

  • It’s added, I apologize for the inconvenience...

1 answer

1


Can be sent when the event ends:

pdfMake = printer.createPdfKitDocument(docDefinition);
let stream = pdfMake.pipe(fs.createWriteStream('../pdfs/Tabela.pdf'));
pdfMake.end();

stream.on('finish', function() {
    if(fs.existsSync('C:/ProjetosLeonardo/Relatorios/pdfs/Tabela.pdf')) {
        let file = 'C:/ProjetosLeonardo/Relatorios/pdfs/Tabela.pdf';
        res.download(file);
    }
}

You can "listen" to certain events because Streams are EventEmitter, so you will be able to detect when it is finished.

  • 1

    It worked perfectly, as I expected. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.