Search code examples
node.jscompressionnode.js-connect

Compressing JSON in node.js


I have a server in nodejs written using Connect. I am exposing some data as JSON. I have to compress the data before sending. I used the compress function in Connect but I am not sure how to check the data if it's compressed or not. Below is my code:

var connect = require('connect')
 , http = require('http');

var app = connect()

 .use(connect.compress(console.log("I have compressed data")))

.use(function(req, res){
res.setHeader('Content-Type', 'application/json');
//res.end("store_id: 'S3000981'");

res.end('{"store_id": "S3000990"}');
});
http.createServer(app).listen(3000);

Any idea regarding this will be really helpful.


Solution

  • Run your server, and try this:

    curl -H 'Accept-Encoding: gzip' -v localhost:3000 
    

    If you see the following appear, the response is compressed:

    < Content-Encoding: gzip
    

    Also, this doesn't do what you think it will, and might have side-effects:

    .use(connect.compress(console.log("I have compressed data")))
    

    If you want to log a message from your server when the response data is compressed, try this instead:

    .use(connect.compress())
    .use(function(req, res, next) {
      res.on('header', function() {
        var encoding = res.getHeader('Content-Encoding') || '';
        if (encoding.indexOf('gzip') != -1 || encoding.indexOf('deflate') != -1)
        {
          console.log("I have compressed data");
        }
      });
      next();
    })