Compression and decompression of data using zlib in Nodejs
有人可以向我解释zlib库如何在Nodejs中工作吗?
我对Node.js还是很陌生,但是我不确定如何使用缓冲区和流。
我的简单场景是一个字符串变量,我想将字符串压缩或解压缩(压缩或膨胀,gzip或gunzip等)到另一个字符串。
即 (我希望它如何工作)
1 2 3 4 5 6 | 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"; |
感谢您的帮助:)
对于任何在2016年绊脚石的人(还想知道如何将压缩数据序列化为字符串而不是文件或缓冲区),zlib(自节点0.11起)现在提供了其函数的同步版本,不需要回调:
1 2 3 4 5 6 7 | 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); |
更新:没意识到节点0.5中有一个新的内置" zlib"模块。我在下面的答案是针对第三方node-zlib模块的。会暂时更新内置版本的答案。
更新2:似乎内置的" zlib"可能有问题。该文档中的示例代码对我不起作用。生成的文件不可压缩(对我来说,"文件结尾意外"失败)。另外,该模块的API并非特别适合您要尝试执行的操作。它更多地用于处理流而不是缓冲区,而node-zlib模块具有更简单的API,更易于用于缓冲区。
使用第三方node-zlib模块进行放气和充气的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $ 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' |
broofa的答案很好,而这正是我希望事情能够进行的方式。对我而言,node坚持回调。最终看起来像:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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") ); }); }); |
这使:
1 2 3 | 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 |