Node.js: Gzip

Node.js: Gzip compression?

// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
var zlib = require('zlib');
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response){
  var raw = fs.createReadStream('index.html');
  var acceptEncoding = request.headers['accept-encoding'];
  if(!acceptEncoding){
    acceptEncoding ='';
  }

  // Note: this is not a conformant accept-encoding parser.
  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
  if(acceptEncoding.match(/\bdeflate\b/)){
    response.writeHead(200,{'content-encoding':'deflate'});
    raw.pipe(zlib.createDeflate()).pipe(response);
  }elseif(acceptEncoding.match(/\bgzip\b/)){
    response.writeHead(200,{'content-encoding':'gzip'});
    raw.pipe(zlib.createGzip()).pipe(response);
  }else{
    response.writeHead(200,{});
    raw.pipe(response);
  }
}).listen(1337);
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s