使用 requestPromise npm 将 Puppeteer 生成的 Pdf 发送到另一个微服务

问题描述

我有两个微服务:1) 我使用 Puppeteer 生成 pdf,它本质上是一个 Buffer 对象。从这项服务,我想将 pdf 发送到另一个微服务,2)它接收请求中的 pdf 并使用 mailgun 将其附加到电子邮件中(一旦我能够将 pdf 从一个服务发送到另一个服务,作为电子邮件附加就不会很困难) . 我在 requestpromise 中发送 pdf 的方式是这样的:

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

但是这样做,我会收到“ERR_STREAM_WRITE_AFTER_END”错误。由于其他服务将电子邮件发送给用户,我如何将此 pdf 从一项服务发送到另一项服务?

解决方法

我已经从前端完成了:

fetch(url,{
  method: 'POST',headers: {
   'Content-Type': 'application/pdf'
  },body: pdfData
}

在这种情况下,pdfData 是一个 blob,所以你需要一个 polyfill 加上 node-fetch

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

发送 body 中的缓冲区。


收货服务:
const pdf = Buffer.from(body.buffer,"base64");
fs.write("file.pdf",pdf,()=> {});