daryl daryl - 5 months ago 24
Node.js Question

Gzip not working for `fs.createReadStream`

For some reason gzip isn't being applied to my read stream, and I'm not sure why.

Here's the function I have written,

body
will always either be a stream from
fs.createReadStream
or just a raw string. The gzip will be applied if I pass in a string, but not when using a stream.

export function send(res, code, body) {
res.setHeader('Content-Encoding', 'gzip');
res.writeHead(code);

if(body instanceof Stream) {
body.pipe(zlib.createGzip());
body.pipe(res);
return;
}

body = zlib.gzipSync(body);

res.end(body);
}


I get this error in Chrome:

ERR_CONTENT_DECODING_FAILED


Any thoughts?

Answer

It should be body.pipe(zlib.createGzip()).pipe(res);, you are sending original stream