节点v0.6.x具有稳定的zlib模块现在在core中-文档中也有一些关于如何在服务器端使用它的示例。
一个例子(取自文档):
// 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(/deflate/)) {
response.writeHead(200, { content-encoding : deflate });
raw.pipe(zlib.createDeflate()).pipe(response);
} else if (acceptEncoding.match(/gzip/)) {
response.writeHead(200, { content-encoding : gzip });
raw.pipe(zlib.createGzip()).pipe(response);
} else {
response.writeHead(200, {});
raw.pipe(response);
}
}).listen(1337);