How to use Node.js zlib module with options?

前提是你 提交于 2019-12-05 04:28:31

Use zlib. createGzip/createDeflate to get an instance of the compressor you need, with options in an object.

If you want to do this all in-memory:

var zlib = require('zlib');

// create a new gzip object
var gzip = zlib.createGzip({
    level: 9 // maximum compression
}), buffers=[], nread=0;

// attach event handlers...

gzip.on('error', function(err) {
    gzip.removeAllListeners();
    gzip=null;
});

gzip.on('data', function(chunk) {
    buffers.push(chunk);
    nread += chunk.length;
});


gzip.on('end', function() {
    var buffer;
    switch (buffers.length) {
        case 0: // no data.  return empty buffer
            buffer = new Buffer(0);
            break;
        case 1: // only one chunk of data.  return it.
            buffer = buffers[0];
            break;
        default: // concatenate the chunks of data into a single buffer.
            buffer = new Buffer(nread);
            var n = 0;
            buffers.forEach(function(b) {
                var l = b.length;
                b.copy(buffer, n, 0, l);
                n += l;
            });
            break;
    }

    gzip.removeAllListeners();
    gzip=null;

    // do something with `buffer` here!
});

// and finally, give it data to compress
gzip.write(inputBuffer);
gzip.end();

Of course, if you're dealing with large amounts of data, stream the output to a file rather than buffering everything in memory.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!