nodejs stream finish callback after pipe is not launched nodejs stream finish callback after pipe is not launched node.js node.js

nodejs stream finish callback after pipe is not launched


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");


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);


pdf is meant to be read from not written to. That means you should be treating it as a Readable stream, so listen for finish on pdfFile instead and remove pdf.end().