admin管理员组

文章数量:1302379

I have a problem with next.js and PDFKit stream. When I create new PDFDocument, convert the stream into new Readable stream and push the data to response, client receives data when doc.end() is fired even though readableStream receives data immediately.

function convertStream(data: any): ReadableStream {
  const readableStream = new ReadableStream({
    start(controller) {
      data.on("data", (chunk: any) => {
        controller.enqueue(chunk);
      });

      data.on("end", () => {
        controller.close();
      });

      data.on("error", (err: Error) => {
        controller.error(err);
      });
    },
    cancel() {
      data.end();
    },
  });

  return readableStream;
}
    const doc = new PDFDocument();
const stream = convertStream(doc);

//doc content
doc.end();
return new Response(stream, headers);

When I use the same convert function on fs.createReadStream data is pushed to client right away. Please help.

本文标签: Nextjs and PDFKit stream to response problemStack Overflow