Next JS 13 app/api/ - stream file back to browser/client

299 views Asked by At
const randomStr = (): string => {
  const characters = "abcdefghijklmnopqrstuvwxyz0123456789";
  let str = "";

  for (let i = 0; i < 10; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    str += characters[randomIndex];
  }

  return str;
};


export const downloadHeaders = (fileName: string) => {
  const headers = {};
  headers["Content-Disposition"] = `attachment; filename=${fileName}`;
  headers["Content-Type"] = "text/plain";
  return headers;
};

const getHugeTXTFile = async (req: NextRequest, ctx: AppRouteHandlerFnContext) => {
  const stream = new ReadableStream({
      async start(controller) {

        for(let i=0; i<= 2000000; i++){
            controller.enqueue(randomStr());
            controller.enqueue("\r\n");
        }
        controller.close();
      },
    });

    return new Response(dataExporter.stream(), {
      headers: downloadHeaders("download-file.txt"),
    });

    /*
    // I have tried this also
    return new NextResponse(dataExporter.stream(), {
      headers: downloadHeaders(fileName),
    })*/
}

export default getHugeTXTFile;

I don't want to use res: NextApiResponse as my 2nd param. How can I stream back a big CSV file in chunks instead of loading the whole CSV file in memory? I'm using NextJS 13 and app/api/file-download/route.ts I'm not using pages/api. Currently, this code does not start downloading from the browser/client side immediately, it waits until everything is in memory on the server side and then pushes it.

0

There are 0 answers