在node.js中的JSON Zip Response

我很新的node.js,我试图发回一个包含JSON结果的zip文件。 我一直在试图找出如何去做,但没有得到预期的结果。

我使用NodeJS,ExpressJS,LocomotiveJS,Mongoose和MongoDB。

由于我们正在构build一个面向移动的应用程序,因此我尽可能多地保存带宽。

移动应用的每日初始负载可能是一个很大的JSON文档,所以我想在将它发送到设备之前进行压缩。 如果可能的话,我想在内存中做所有的事情,以避免磁盘I / O。

到目前为止,我尝试了3个库:

  • ADM-ZIP
  • 节点拉链
  • zipstream

我实现的最好结果是使用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文件,但内容是不可读的。

我很确定我正在混合的东西,但到现在我不知道如何进行。

有什么build议吗?

感谢advace

你可以用下面的expression式3来压缩输出:

 app.configure(function(){ //.... app.use(express.compress()); }); app.get('/foo', function(req, res, next){ res.send(json_data); }); 

如果用户代理支持gzip,它会自动为你自动gzip。

对于Express 4+,压缩不会与Express捆绑在一起,需要单独安装。

 $ npm install compression 

然后使用库:

 var compression = require('compression'); app.use(compression()); 

有一堆你可以调整的选项, 看这里的列表 。

我认为你的意思是我怎样向节点发送Gzip内容?

节点版本0.6及以上具有内置的zlip模块,因此不需要外部模块。

你可以发送像这样的Gzip内容。

  response.writeHead(200, { 'content-encoding': 'gzip' }); json.pipe(zlib.createGzip()).pipe(response); 

显然你需要首先检查天气客户端接受Gzip编码,还记得gzip是一个昂贵的操作,所以你应该caching结果。

这里是从文档中完整的例子

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