我对node.js非常陌生,我正试图发送一个包含JSON结果的zip文件。我一直在想怎么做,但还没有达到预期的效果。
我用的是NodeJS,ExpressJS,LocomotiveJS,Mongoose和MongoDB。
由于我们正在构建一个面向移动的应用程序,我正在尽可能多地保存带宽。
移动应用程序的每日初始负载可能是一个大的JSON文档,所以我想在将其发送到设备之前将其压缩。如果可能的话,我想做所有内存中的事情,以避免磁盘I/O。
到目前为止,我尝试了三个库:
我所取得的最好结果是使用node。这是我的密码:
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文件,但内容不可读。
我很确定我把事情搞混了,但到目前为止,我不知道该怎么做。
有什么建议吗?
先谢
发布于 2012-09-25 23:15:59
您可以使用以下方式压缩速成3中的输出:
app.configure(function(){
//....
app.use(express.compress());
});
app.get('/foo', function(req, res, next){
res.send(json_data);
});如果用户代理支持gzip,它将自动为您提供gzip。
发布于 2017-04-26 14:42:05
对于Express 4+,压缩不与Express捆绑在一起,需要单独安装。
$ npm install compression然后使用库:
var compression = require('compression');
app.use(compression());有很多选项可以调优,见这里的清单。
发布于 2012-09-25 22:30:27
我认为您的意思是如何通过节点发送Gzip内容?
节点版本0.6及以上版本有内置的兹利普模块,因此不需要外部模块。
您可以像这样发送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);https://stackoverflow.com/questions/12591861
复制相似问题