Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compressed responses #10

Open
limadm opened this issue Sep 18, 2018 · 0 comments
Open

Compressed responses #10

limadm opened this issue Sep 18, 2018 · 0 comments

Comments

@limadm
Copy link

limadm commented Sep 18, 2018

Hello,

When using ajax-request to download static assets from a cdn, some of the proxies/mirrors compress the response body, signaling so in the content-encoding response header (MDN docs).
It would be great if ajax-request could detect and uncompress these responses, or at least provide a pipeline callback for the users to uncompress the response body on-the-fly before writing to disk.

For now I have been rewriting the destination in simple scenarios (only one content-encoding) in the download callback, somewhat like:

const ajaxRequest = require('ajax-request');
const fs = require('fs');
const zlib = require('zlib');

ajaxRequest.download({
  url: 'https://my.cdn.org/lib/file.js',
  destPath: () => './js/assets/file.js',
}, (err, res, body, destpath) => {
  if (err) {
    console.log('Download failed!', err);
  } else {
    var supported = ['gzip','x-gzip','deflate'];
    var encoding = res.headers['content-encoding'];
    if (supported.includes(encoding)) {
      fs.createWriteStream(destpath).pipe(zlib.createUnzip()).pipe(body);
    }
  }
});

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant