本文介绍了在Nodejs中使用zlib对数据进行压缩和解压缩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 有人可以向我解释zlib库如何在Nodejs中工作吗?Can someone please explain to me how the zlib library works in Nodejs?我对Nodejs很新,我还不确定如何使用缓冲区和流。I'm fairly new to Nodejs, and I'm not yet sure how to use buffers and streams.我的简单场景是一个字符串变量,我想要压缩或解压缩(放大或膨胀,gzip或gunzip等)字符串另一个字符串。My simple scenario is a string variable, and I want to either zip or unzip (deflate or inflate, gzip or gunzip, etc') the string to another string. (我如何期望它的工作)I.e. (how I would expect it to work)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模块。将立即更新内置版本的答案。Update: Didn't realize there was a new built-in 'zlib' module in node 0.5. My answer below is for the 3rd party node-zlib module. Will update answer for the built-in version momentarily. 更新2 :看起来内部'zlib可能有问题'。文档中的示例代码不适用于我。生成的文件不是gunzip'able(失败与意外的文件结束对我来说)。此外,该模块的API不是特别适合您想要做的。它更多的是使用流而不是缓冲区,而node-zlib模块有一个更简单的API,更容易使用缓冲区。Update 2: Looks like there may be an issue with the built-in 'zlib'. The sample code in the docs doesn't work for me. The resulting file isn't gunzip'able (fails with "unexpected end of file" for me). Also, the API of that module isn't particularly well-suited for what you're trying to do. It's more for working with streams rather than buffers, whereas the node-zlib module has a simpler API that's easier to use for Buffers.使用第三方node-zlib模块缩小和膨胀的示例:An example of deflating and inflating, using 3rd party node-zlib module:$ 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' 这篇关于在Nodejs中使用zlib对数据进行压缩和解压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-22 06:17