我对node.js很陌生,我试图发送一个包含JSON结果的zip文件。 我一直试图弄明白该怎么做,但没有达到预期的效果。
我正在使用NodeJS,ExpressJS,LocomotiveJS,Mongoose和MongoDB。
由于我们正在构建面向移动设备的应用程序,我试图尽可能多地保存带宽。
移动应用的每日初始加载可能是一个大的JSON文档,因此我想在将其发送到设备之前将其压缩。如果可能的话,我希望在内存中完成所有操作以避免磁盘I / O.
到目前为止我尝试了3个库:
我实现的最佳结果是使用node-zip。这是我的代码:
return Queue.find({'owners': this.param('id')}).select('name extra_info cycle qtype purge purge_time tasks').exec(function (err, docs) {
if (!err) {
zip.file('queue.json', docs);
var data = zip.generate({base64:false,compression:'DEFLATE'});
res.set('Content-Type', 'application/zip');
return res.send(data);
}
else {
console.log(err);
return res.send(err);
}
});
结果是下载的zip文件,但内容不可读。
我很确定我会把事情搞混,但到目前为止我还不确定如何继续。
有任何建议吗?
先谢谢
答案 0 :(得分:17)
您可以使用以下方法压缩快递3中的输出:
app.configure(function(){
//....
app.use(express.compress());
});
app.get('/foo', function(req, res, next){
res.send(json_data);
});
如果用户代理支持gzip,它会自动为您进行gzip。
答案 1 :(得分:1)
我认为你的意思是我如何通过节点发送Gzip内容?
节点版本0.6及更高版本具有内置zlip模块,因此无需外部模块。
您可以像这样发送Gzip内容。
response.writeHead(200, { 'content-encoding': 'gzip' });
json.pipe(zlib.createGzip()).pipe(response);
显然你需要首先检查天气,客户端接受Gzip编码,还记得gzip是一项昂贵的操作,所以你应该缓存结果。
以下是从文档中获取的完整示例
// 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);
} else if (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);
答案 2 :(得分:1)
对于Express 4+,压缩不与Express捆绑在一起,需要单独安装。
$ npm install compression
然后使用该库:
var compression = require('compression');
app.use(compression());
您可以调整许多选项,see here for the list。