This is really old but this still saved me a lot of time.
Solution from leonid-beschastny is correct. However, there is a very subtle difference in the complete sequence of the calls being made. The solutions are all from the experts and a newbie like me gets lost - due to simple differences like - how a stream is being created or the objects missed in the description.
Also, this is a generic solution to a lot of other scenarios. When you are piping to a writableStream - and by the time async function that contains this operation - returns. The streaming is not complete - so the probable image/document/pdf that is being piped to - is not yet created. It will be of size 0 KB.
Sharing here in simple steps.
a. createPdfKitDocument with your definition as required.
b. Create the writeStream the way you want as per your design.
c. Pipe your prepared document to this stream.
d. Add this finish event to your writeStream.
e. Most important - without this it doesn't work.
Here
var pdfStream = printer.createPdfKitDocument(docDefinition); //a
let writerStream = fs.createWriteStream(fullfileName); //b
pdfStream.pipe(writerStream); //c
writerStream.on('finish', function () {
//This could be your callback function.
callback());
}) //d
pdfStream.end(); //e
I also referred to these links - they might help someone
a. PDF download fails using PDFMake in NodeJS This gave me the clue to post.
Main issue is - createWriteStream is not finished [due to whatever reasn] - by the time the async function that contains it - returns.
Also leonid-beschastny is right in saying that race condition won't occur - I test my code by swapping the position of the pdfStream.pipe(writerStream);
and
writerStream.on('finish', function () {
//This could be your callback function.
callback());
})
Hope it helps few more people.