如何使用带有选项的 Node.js zlib 模块? [英] How to use Node.js zlib module with options?

查看:31
本文介绍了如何使用带有选项的 Node.js zlib 模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Node.js 中使用 zlib 在极端压缩级别压缩缓冲区.输出的标头应为 78 DA.除非我遗漏了什么,否则 Node.js 文档并没有真正描述如何使用 zlib.Deflate 类.它不接受任何参数.

I need to compress a buffer in Node.js with zlib at the extreme compression level. The outputted header should be 78 DA. Unless I'm missing something, the Node.js documentation doesn't really describe how to use the zlib.Deflate class. It doesn't accept any parameters.

http://nodejs.org/api/zlib.html#zlib_class_zlib_deflate

推荐答案

使用 zlib. createGzip/createDeflate 获取您需要的压缩器,带有对象中的选项.

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.

这篇关于如何使用带有选项的 Node.js zlib 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆