Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs stream finish callback after pipe is not launched

I need to do some housekeeping after pdf file is saved:

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 code inside second nested function is never launched. pdf is object from pdfkit library. How can I fix it?

UPD: this approach doesn't work also:

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);
like image 330
Stepan Yakovenko Avatar asked Aug 23 '15 12:08

Stepan Yakovenko


2 Answers

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

console.log("saving file");

pdf
  .pipe( fs.createWriteStream("./test2.pdf") )
  .on( 'finish', function(){
    console.log("Finished");
  });
pdf.end();

console.log("After save");
like image 140
stdob-- Avatar answered Nov 17 '22 16:11

stdob--


If pdf is a proper NodeJS stream, you can simply pipe it into the write stream and be done. If you want to quit your program after the file is saved, you could do this on 'close'. Notice: there is no "after saving" state (because you end the process). That console.log("After save") line 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);
like image 39
regular Avatar answered Nov 17 '22 15:11

regular