Dino
Dino

Reputation: 1347

Gzip files and Angular 2

I have some file zipped using gzip (.gz file type) stores on my server.

I use a service (Angular 2) and an observable to download the file to the client machine:

this.rest.getFile(this.stlLocation).subscribe(
            data => {

                    console.log(data);
                    //OK, now I have my .gz file containing a compressed JSON file. 
                    //What do I need to do in angular 2 to decompress and read the JSON data in the file?

                },
                err => {
                    this.msgs.push({severity: 'error', summary: 'Error Message', detail: err});
                }
            );

How can I unzip and get the plain JSON file once successfully downloaded?

updates...

Thank you to joh for sending me on the right path. See accepted answer. After a bit of reading, I have implemented the following solution.

According to Joh:

"If you are downloading the file to a browser, you shouldn't have to do anything. Browsers add the Accept-Encoding: 'deflate' header automatically; it is both unnecessary and not good practice to do this at a DOM/JS level."

If you are using NGINX the following link may help you out:

NGINX COMPRESSION AND DECOMPRESSION

A massive thank you to all the other people that tried to help with different solutions. I really appreciate the time you took try answering my question.

Upvotes: 0

Views: 9507

Answers (2)

joh04667
joh04667

Reputation: 7427

If you are downloading the file to a browser, you shouldn't have to do anything. Browsers themselves add the Accept-Encoding: 'deflate' header automatically; it is both unnecessary and not good practice to do this at a DOM/JS level because the browser should take care of this for you. GZipping was meant for network transfer, and encoding is handled in request headers; the browser should unwrap this for you.

So, once you have the file, it should be usable as JSON (if using Angular's Http service, you will have to parse the JSON i.e. Observable.map(res => res.json()) ).

Side note: if this uncompressed file is under ~1.4Kb, it's probably better off left un-gzipped. Files that small are going to be sent in a single packet anyway, and gzipping will just add a small overhead to the DOM and CPU.

Upvotes: 1

Erica Grant
Erica Grant

Reputation: 260

If you are using npm you could use something like this: https://www.npmjs.com/package/gzipy

from usage:

 //Import gzipy  
var gzipy = require('gzipy');

//Compress a file  
gzipy.compress('./file.txt', './file.txt.gz', function(error)
{
  //Handle the error  
  if(error){ /* Something went wrong... */ } 

  console.log('File compressed!');
});

//Decompress a file 
gzipy.decompress('./document.pdf.gz', './document.pdf', function(error)
{
  //Handle the error  
  if(error){ /* Something went wrong... */ } 

  console.log('File decompressed');
});

Upvotes: 0

Related Questions