JSON Zip Response in node.js

前端 未结 3 616
一向
一向 2021-02-04 18:04

I\'m pretty new to node.js and I\'m trying to send back a zip file containing JSON results. I\'ve been trying to figure it out how to do it, but haven\'t had the expected result

3条回答
  •  清歌不尽
    2021-02-04 18:47

    I think you mean how do I send Gzip content with node?

    Node version 0.6 and above have a built in zlip module, so there is no need to require external modules.

    You can send Gzip content like this.

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

    Obviously you will need to first check weather the client accepts the Gzip encoding and also remember gzip is a expensive operation so you should cache the results.

    Here is full example taking from the docs

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

提交回复
热议问题