Synchronous function to check files in NodeJS?

0

I'm creating PDF's on my NodeJS server using the Express framework and the PdfMake library. If someone looks at my profile I will see that I asked a question about corrupted PDF after download. It turns out that I have discovered that the files are corrupted because they are sent to download before even the creation of them is completed, because the whole process happens asynchronously. What I need to know is the following: With which SYNCHRONOUS process could I check if 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()
    })
    
asked by anonymous 15.08.2017 / 21:29

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 "hear" certain events because Streams are EventEmitter , so you'll be able to detect when it's finished.

    
15.08.2017 / 22:03