0

I am using Node.js as a HTTP server. I do not use the Express module. I want to compress a javascript file, send the resulting string after setting headers in the middleware, as in:

    zlib = require ("zlib");
    res.setHeader('Content-Encoding', 'gzip');
    res.setHeader('Content-Type', 'text/javascript');
    
    //Compress the javascript
    zlib.gzip(js_string, (err, buffer) => { //js_string is a string not buffer
       if (err) {
            //processError...
       }
       else {
           res.end(buffer.toString('hex'));
       }
    });

The questions that I have are:

  1. zlib.gzip has a second parameter called options. What options, if any, do I need to specify if the gzip is created to be unzipped by the browser?
  2. What kind of buffer-to-string encoding is to be done, 'hex', 'base64',... again if the usage is for creating a compressed content to be uncompressed by the browser? Should I be using "Content-Transfer-Encoding" header to indicate to the browser the encoding type?
Sunny
  • 9,245
  • 10
  • 49
  • 79
  • 1
    `zlib.gzip has a second parameter called options` - are you sure? they don't seem to be documented anywhere - only seems to take one argument of options which are documented [here](https://nodejs.org/dist/latest/docs/api/zlib.html#class-options) - I think the default options are OK - https://zlib.net/manual.html#Advanced if you want to play with them of course ... you are using the node built-in zlib I hope – Jaromanda X Oct 04 '22 at 06:00
  • 1
    as far as 2. goes ... you don't want `hex` - that is twice the size of binary, `base64` would be 33% larger than binary ... just use the example code from node itself - https://nodejs.org/dist/latest/docs/api/zlib.html#compressing-http-requests-and-responses - which will use `deflate`, `gzip`, `br` or no compression, depending on what the client accepts – Jaromanda X Oct 04 '22 at 06:04
  • @JaromandaX Thanks for the link. Big help. I am trying it now. Its a little complex than what I have described as I also have a Nginx reverse proxy in between which is set up properly for gzip processing. I think it will do nothing as far as compression is concerned because I am not passing a file to it to be served. I read all files and serve them using res.end(contentString). Unsure how nginx will handle the compression in this case. Until I realized that browsers were not getting response with content-encoding set to gzip, all was working fine. – Sunny Oct 04 '22 at 06:35
  • @JaromandaX Your comments and the link in particular helped me to solve the issues I had. The whole area is interesting... choice of compression algo, security issues, performance tradeoffs, etc. If you provide your comments as an answer, specifically highlighting the link to node.js zlib, I will be happy to accept it. – Sunny Oct 05 '22 at 09:57

0 Answers0