expressjs / expressjs.com

Home Page:https://expressjs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to flush a response?

JasonKleban opened this issue · comments

When I run this sample on express v4.18.2, I don't see any of the response data in the Chrome Debugger Network Tab nor in Fiddler until after the 15 second mark. This is despite that "First part was piped" shows up immediately in the server side console. How can I force the response stream to be flushed, please?

import { Readable } from "stream";

app.get("/api/data/multipart", (request, response, next) => {
    response.useChunkedEncodingByDefault = true;
    response.status(200);

    const p1 = Readable.from("Foo".repeat(1000))
    p1.on('close', () => {
        console.log(`First part was closed`);
    });
    p1.pipe(response, { end: false });

    console.log(`First part was piped`);

    global.setTimeout(() => {
        Readable.from("Bar".repeat(1000)).pipe(response, { end: true });

        console.log(`Second part was piped`);
        next();
    }, 15 * 1000);
});

Output:

First part was piped << Immediate
First part was closed << Immediate
Second part was piped << ~15s

Oops, I posted this in the wrong repo. I will close here and reopen in the right one.