Home>

Using Node.js, the gzip-compressed html file is returned as a response in the following format.

constant hoge='huga';
res.setHeader ('Content-Disposition','attachment; filename= test.html.gz');
res.setHeader ('Content-Encoding','gzip');
res.setHeader ('Content-Type','text /html; charset= UTF-8');
zlib.gzip (hoge, (err, result)= >
 {
  res.send (result);
});

When you hit an endpoint with the above processing,test.html.gzCan be downloaded, but
I get an error when unzipping gzip.

Edit the file name directly andtest /htmlThen it can be opened as an html file, so I think that it has not been compressed into gzip.
How can I get gzip compression and response successfully?

Perhaps it seems that you are using expressjs, but do you mean that you want to realize it without using a library?

himenon2021-09-23 18:20:00

If you set the Content-Type to text /html, the browser will automatically restore it. Try changing the Content-Type to application /x-gzip.

metropolis2021-09-23 18:20:00

Yes. I am using expressjs. There is no problem with using the library in situations where you want to gzip text /html and respond and achieve a state where the file can be answered normally. I changed the Content-Type to application /x-gzip and tried it, but the behavior did not change.

NaG2021-09-23 18:20:00

What happens if I try to output it as a file instead of outputting it with a browser and unzip it directly to isolate the problem?

keitaro_so2021-09-23 18:20:00
  • Answer # 1

    If you want to gzip the response with express.js,compressionI think it is common to use (because it is also written in the document).

    Below is the sample code.http: //localhost: 3000Please visit and check with DevTools.

    server.jsSave it likenode server.jsTry running as. Please note that if the Content to be included in the response is too small, it will not be gzipped. In the sample code, the for-loop is intentionally turned.

    const expres= require ("express");
    const compression= require ("compression");
    const app= expres ();
    app.use (compression ({
      threshold: 0,
    }));
    const domText= [];
    for (let i= 0; i <
     10; i ++) {
      domText.push (`<
    li >
    Random Number $ {Math.random ()} <
    /li >
    `);
    }
    const htmlText= `<
    ! DOCTYPE html >
    ≪
    html lang= "en" >
    ≪
    head >
      ≪
    meta charset= "UTF-8" >
      ≪
    meta http-equiv= "X-UA-Compatible" content= "IE= edge" >
      ≪
    meta name= "viewport" content= "width= device-width, initial-scale= 1.0" >
      ≪
    title >
    Hello world page <
    /title >
    ≪
    /head >
    ≪
    body >
      ≪
    h1 >
    Hello world from express.js <
    /h1 >
      ≪
    ul >
      $ {domText.join ("\ n")}
      ≪
    /ul >
    ≪
    /body >
    ≪
    /html >
    `;
    app.get ("/", (req, res)= >
     {
      res.send (htmlText);
      res.end ();
    });
    app.listen (3000, ()= >
     {
      console.log ("Start server: http: //localhost: 3000");
    });
    

    For those who are interested

    Although it may deviate from the purpose of the question, the pattern to be written without using the library is as follows.

    const http= require ("http");
    const zlib= require ("zlib");
    const availableGzip= (header)= >
     {
      return typeof header=== "string" &
    &
     Boolean (header &
    &
     /gzip/i.test(header));
    };
    const htmlText= `<
    ! DOCTYPE html >
    ≪
    html lang= "en" >
    ≪
    head >
      ≪
    meta charset= "UTF-8" >
      ≪
    meta http-equiv= "X-UA-Compatible" content= "IE= edge" >
      ≪
    meta name= "viewport" content= "width= device-width, initial-scale= 1.0" >
      ≪
    title >
    Hello world page <
    /title >
    ≪
    /head >
    ≪
    body >
      ≪
    h1 >
    Hello world <
    /h1 >
    ≪
    /body >
    ≪
    /html >
    `;
    const rootRouter= (req, res)= >
     {
      const message= htmlText;
      if (availableGzip (req.headers ["accept-encoding"])) {
        zlib.gzip (Buffer.from (message), (err, data)= >
     {
          res.setHeader ("Content-Encoding", "gzip");
          res.setHeader ("Content-Length", data.byteLength);
          res.setHeader ("Content-Type", "text /html; charset= UTF-8");
          res.writeHead (200);
          res.end (data);
        });
      } else {
        res.setHeader ("Content-Length", message.length);
        res.writeHead (200);
        res.end (message);
      }
    };
    const notFoundRouter= (req, res)= >
     {
      res.write ("Not found page");
      res.end ();
    };
    const requestListener= (req, res)= >
     {
      switch (req.url) {
        case "/":
          rootRouter (req, res);
          break;
        default: default:
          notFoundRouter (req, res);
          break;
      }
    };
    const server= http.createServer (requestListener);
    server.listen (3000);
    console.log ("Server start: http: //localhost: 3000");
    

    Reference: Compress text resources to improve website performanceThere is a little more information on.