Early exit from Cloudflare HTMLReWriter

Viewed 49

I am building a Cloudflare Worker that uses HTMLRewriter to parse some items out of an HTML stream.

Since the HTML stream can be quite long, when I have found the last item I am looking for I would like stop further action from HTMLRewriter and return my JSON response immediately.

I looked into throwing an error to achieve this but that seems to get logged as a failure case in the analytics.

Is there a better way to early-exit HTMLRewriter and still return a JSON response?

1 Answers

You'd have to buffer the response somehow. A successful operation (where you're returning HTML) would look like: process the document with HTMLRewriter, stream processed output to a buffer, and finally send the HTML response from the buffer. To swap it to JSON, you'd detect that scenario and return the JSON response instead of the HTML buffer. I'd imagine you could throw an exception from your HTMLRewriter handler and then catch that that exception in the code that would normally send the buffered response.

Overall, this is sort of a weird use case: the HTMLRewriter API is supposed to be streaming, so everything is designed so you can stream chunks to the client as they are processed. Hence the need to buffer the response in the Cloudflare Worker.

Related