在Nodejs中使用zlib压缩和解压缩数据

有人可以请向我解释zlib库如何在Nodejs中工作?

我对Nodejs相当陌生,而且我还不确定如何使用缓冲区和stream。

我的简单场景是一个stringvariables,我想压缩或解压缩(压缩或膨胀,gzip或gunzip等)的string到另一个string。

即(我如何期待它的工作)

var zlib = require('zlib'); var str = "this is a test string to be zipped"; var zip = zlib.Deflate(str); // zip = [object Object] var packed = zip.toString([encoding?]); // packed = "packedstringdata" var unzipped = zlib.Inflate(packed); // unzipped = [object Object] var newstr = unzipped.toString([again - encoding?]); // newstr = "this is a test string to be zipped"; 

感谢您的帮助:)

更新 :没有意识到节点0.5中有一个新的内置“zlib”模块。 我的答案在于第三方node-zlib模块 。 将立即更新内置版本的答案。

更新2 :看起来像内置的“zlib”可能有问题。 文档中的示例代码不适用于我。 由此产生的文件是不能gunzip'able(失败与“意外结束的文件”对我来说)。 而且,该模块的API并不是特别适合你所要做的。 它更多的是使用stream而不是缓冲区,而node-zlib模块有一个更简单的API,可以更容易地用于缓冲区。


使用第三方node-zlib模块进行缩减和膨胀的示例:

 $ node > // Load zlib and create a buffer to compress > var zlib = require('zlib'); > var input = new Buffer('lorem ipsum dolor sit amet', 'utf8') > // What's 'input'? > input <Buffer 6c 6f 72 65 6d 20 69 70 73 75 6d 20 64 6f 6c 6f 72 20 73 69 74 20 61 6d 65 74> > // Compress it > zlib.deflate(input) <SlowBuffer 78 9c cb c9 2f 4a cd 55 c8 2c 28 2e cd 55 48 c9 cf c9 2f 52 28 ce 2c 51 48 cc 4d 2d 01 00 87 15 09 e5> > // Compress it and convert to utf8 string, just for the heck of it > zlib.deflate(input).toString('utf8') 'x???/J?U?,(.?UH???/R(?,QH?M-\u0001\u0000?\u0015\t?' > // Compress, then uncompress (get back what we started with) > zlib.inflate(zlib.deflate(input)) <SlowBuffer 6c 6f 72 65 6d 20 69 70 73 75 6d 20 64 6f 6c 6f 72 20 73 69 74 20 61 6d 65 74> > // Again, and convert back to our initial string > zlib.inflate(zlib.deflate(input)).toString('utf8') 'lorem ipsum dolor sit amet' 

对于任何人在2016年遇到困难(也想知道如何将压缩数据序列化为string而不是文件或缓冲区) – 它看起来像zlib(因为节点0.11)现在提供了不需要callback函数的同步版本:

 var zlib = require('zlib'); var input = "Hellow world"; var deflated = zlib.deflateSync(input).toString('base64'); var inflated = zlib.inflateSync(new Buffer(deflated, 'base64')).toString(); console.log(inflated); 

broofa的答案很好,而这正是我想要的东西的工作。 对于我,节点坚持callback。 这最终看起来像:

 var zlib = require('zlib'); var input = new Buffer('lorem ipsum dolor sit amet', 'utf8') zlib.deflate(input, function(err, buf) { console.log("in the deflate callback:", buf); zlib.inflate(buf, function(err, buf) { console.log("in the inflate callback:", buf); console.log("to string:", buf.toString("utf8") ); }); }); 

这使:

 in the deflate callback: <Buffer 78 9c cb c9 2f 4a cd 55 c8 2c 28 2e cd 55 48 c9 cf c9 2f 52 28 ce 2c 51 48 cc 4d 2d 01 00 87 15 09 e5> in the inflate callback: <Buffer 6c 6f 72 65 6d 20 69 70 73 75 6d 20 64 6f 6c 6f 72 20 73 69 74 20 61 6d 65 74> to string: lorem ipsum dolor sit amet