在nodejs中压缩json

我有一个服务器在nodejs写入使用连接。 我正在暴露一些数据为JSON。 发送前我必须压缩数据。 我用连接的压缩function,但我不知道如何检查数据,如果它的压缩或不。 以下是我的代码:

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); 

任何关于这个想法将是非常有帮助的。

运行你的服务器,并试试这个:

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

如果您看到以下内容,则响应会被压缩:

 < Content-Encoding: gzip 

此外,这不符合你的想法,也可能有副作用:

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

如果您希望在响应数据被压缩时从服务器logging消息,请尝试使用此方法:

 .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(); })