Nodejs thread terminates callback after pipe is not running

I need to do some cleaning after saving the PDF file:

docx2pdf(doc, function (pdf) { console.log("saving file"); var pdfFile = fs.createWriteStream("./test2.pdf"); pdf.on('finish',function(){ console.log("Finished"); process.exit(); }).pipe(pdfFile); pdf.end(); console.log("After save"); }, true, true); 

But the code inside the second nested function never runs. pdf is an object of the pdfkit library. How can i fix this?

UPD: this approach also does not work:

 docx2pdf(doc, function (pdf) { console.log("saving file"); var pdfFile = fs.createWriteStream("./test2.pdf"); pdfFile.on('finish',function(){ console.log("Finished"); process.exit(); }); pdf.pipe(pdfFile); //pdf.end(); console.log("After save"); }, true, true); 
+7
stream pipe
source share
3 answers

You need to catch the finish event on the pipe object, not on the pdf file:

 console.log("saving file"); pdf .pipe( fs.createWriteStream("./test2.pdf") ) .on( 'finish', function(){ console.log("Finished"); }); pdf.end(); console.log("After save"); 
+2
source share

pdf intended to be read from the unwritten. This means that you should consider it as a readable stream, so listen to finish on pdfFile and delete pdf.end() .

0
source share

If pdf is the correct NodeJS stream, you can simply pass it to the write stream and execute. If you want to exit the program after saving the file, you can do this when closing. Please note: there is no post-save state (because you are completing the process). This line console.log("After save") in your code is called before the file is saved!

 docx2pdf(doc, function (pdf) { console.log("saving file"); var pdfFile = fs.createWriteStream("./test2.pdf"); pdf.pipe(pdfFile); pdfFile.on('close',function(){ console.log("Finished"); process.exit(); }); }, true, true); 
0
source share

All Articles