Responding gzip using zlib in NodeJS is not compressed

Asked 2 years ago, Updated 2 years ago, 101 views

Using Node.js, we returned the gzip compressed html file as a response in the following form:

 consthoge='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);
});

You can download by tapping an endpoint with the above action.
Error unzipping gzip

If you edit the file name directly and set it to test/html, it can be opened as an html file, so I think it is not compressed into gzip.
How do I successfully perform gzip compression and respond?

javascript node.js gzip

2022-09-30 14:35

1 Answers

If you want to gzip the response in express.js, I think it is common to use compression (as it is mentioned in the document).

The following is the sample code: Go to http://localhost:3000 and check with DevTools

Try saving it like server.js and running it as node server.js.If the content is too small for the response, it will not be gziped, so please be careful.In the sample code, I intentionally turned for-loop.

const express=require("express");
const compression=require("compression");

const app=expres();

app.use(compression({
  threshold —0,
}));

const domText=[];

for(leti=0;i<10;i++){
  domText.push(`<li>Random Number${Math.random()}</li>`);
}

consthtmlText=`<!DOCTYPE html>
<html lang="en">
<head>
  <metacharset="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";
});

Check with DevTools

This may not be the point of the question, but the pattern you write without the library is as follows:

const http=require("http");
const zlib = require("zlib");

constavailableGzip=(header)=>{
  return type of header==="string"&&Boolean(header&/gzip/i.test(header));
};

consthtmlText=`<!DOCTYPE html>
<html lang="en">
<head>
  <metacharset="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>
`;

constrootRouter=(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:
      notFoundRouter(req,res);
      break;
  }
};

const server = http.createServer(requestListener);

server.listen (3000);

console.log("Server start:http://localhost:3000";

Note: Compress text resources to improve website performance contains more information.


2022-09-30 14:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.