Got Async Download and Ungzip File (Node.js)

Jul 27, 2021

Use got to download and uncompress gz file (e.g. https://www.mydomain.com/sitemap.xml.gz)

const got = require('got')const url = ...let response = await got(url); // , decompress: truelet content = nullif (response.headers['content-type'].includes('x-gzip')) {  const zlib = require('zlib');  /*  const gzip = (input, options) => {    const promise = new Promise(function(resolve, reject) {      zlib.gzip(input, options, function (error, result) {        if(!error) resolve(result);        else reject(Error(error));      });    });    return promise;  }   */  const ungzip = (input, options) => {    const promise = new Promise(function(resolve, reject) {      zlib.gunzip(input, options, function (error, result) {        if(!error) resolve(result);        else reject(Error(error));      });    });    return promise;  }  const compressed = response.body  const data = await ungzip(compressed);  content = data.toString()}else {  content = response.body}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.

Tags