Sometimes, we want to decompress a Node.js request’s module gzip response body.
In this article, we’ll look at how to decompress a Node.js request’s module gzip response body.
How to decompress a Node.js request’s module gzip response body?
To decompress a Node.js request’s module gzip response body, we can set the encoding
option to null
and then use the zlib.gunzip
method.
For instance, we write
const request = require('request');
const zlib = require('zlib');
request(url, {
encoding: null
}, (err, response, body) => {
if (response.headers['content-encoding'] === 'gzip') {
zlib.gunzip(body, (err, unzipped) => {
callback(unzipped.toString());
});
} else {
callback(body);
}
});
to call request
with an object that has encoding
set to null
.
Then in the callback, we check if the content-encoding
response header is 'gzip'
.
If it is, then we call zlib.gunzip
to decompress the response body
.
And then we can get the unzipped response contents from the unzipped
parameter in the gunzip
callback.
Conclusion
To decompress a Node.js request’s module gzip response body, we can set the encoding
option to null
and then use the zlib.gunzip
method.