Search code examples
node.jspdfpuppeteerform-datarequest-promise

Send Puppeteer Generated Pdf to another microservice using requestPromise npm


I have two microservices: 1) in which I am generating pdf using Puppeteer, which is essentially a Buffer object. From this service I want to send the pdf to another microservice, 2) which receives the pdf in request and attaches it in email using mailgun (once I am able to send pdf from one service to another, attaching as an email wont be difficult). The way I m sending the pdf in requestpromise is this:

import requestPromise from "request-promise";
import {Readable} from "stream";

//pdfBuffer is result of 'await page.pdf({format: "a4"});' (Puppeteer method).

const stream = Readable.from(pdfBuffer); 
/*also tried DUPLEX and Readable.from(pdfBuffer.toString()) and this code too.
   const readable = new Readable();
   readable._read = () => {}
   readable.push(pdf);
   readable.push(null);
*/

requestPromise({
        method: "POST",
        url: `${anotherServiceUrl}`,
        body: {data},
        formData: {
            media: {
                value: stream,
                options: {
                    filename: "file.pdf",
                    knownLength: pdfBuffer.length,
                    contentType: "application/pdf"
                }
            }
        },
        json: true
    }
});

But doing so, I get "ERR_STREAM_WRITE_AFTER_END" error. How can I send this pdf from one service to another, since the other service sends the email to the user?


Solution

  • const buffer = Buffer.from(pdfBuffer).toString("base64").toString();
    

    sending the buffer in the body.


    On Receiving service:
    const pdf = Buffer.from(body.buffer, "base64");
    fs.write("file.pdf", pdf, ()=> {});