gzip圧縮したファイルをレスポンスとして返す

node.jsでgzipのファイルを返したりするメモ。というかまあ、普通にファイルを返すのとあまりかわらないのだけど。
環境:WindowsXP SP3 / node.js 0.8.2

index.html
<!DOCTYPE html>
<meta charset="utf-8">
<title>インターネット</title>
<style>
  p {
    color: #00f;
    font-size: 2em;
    text-align: center;
  }
</style>
<p>インターネット</p>
app.js
var fs = require('fs'),
    http = require('http'),
    path = require('path'),
    server = http.createServer();

server.on('request', function (req, res) {

  fs.readFile(path.join(__dirname, 'index.html.gz'), function (err, data) {
    if (err) throw err;
    res.writeHead(200, {
      'content-type': 'text/html; charset=utf-8',
      'content-encoding': 'gzip',
      'content-length': data.length
    });
    res.end(data);
  });
});
server.listen(3000);

準備・起動

$ gzip index.html -c > index.html.gz
$ node app.js


これでgzipで返ってきてるはず。まあ、本当はaccept-encodingにgzipが含まれてるかどうか見ないとなんだけど……