To change the Content-Length header in a Cloudflare Worker when serving files from an R2 bucket, you should use a FixedLengthStream to create a stream with a specified length. However, your current code snippet is missing a few steps. Here's how you can modify it:
firmwareBin = await env.R2.get(decodeURI(key));
let { readable, writable } = new FixedLengthStream(175104);
// You need to create a new Response object with the readable stream
// and set the headers you want to modify or keep from the original response.
let newHeaders = new Headers(firmwareBin.headers);
newHeaders.set('Content-Length', '175104'); // Set the desired Content-Length
// Pipe the original body to the writable stream of the FixedLengthStream.
await firmwareBin.body.pipeTo(writable);
// Return a new Response with the readable stream from the FixedLengthStream
// and the new headers.
return new Response(readable, {
headers: newHeaders,
status: firmwareBin.status,
statusText: firmwareBin.statusText
});
Make sure to replace '175104' with the actual length of the content you want to serve. This code creates a new Response object with the readable stream from the FixedLengthStream and sets the Content-Length header to the desired value. It also preserves the original status and status text from the firmwareBin response.