小编典典

在Node.js中使用zlib压缩和解压缩数据

node.js

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

我对Node.js很陌生,还不确定如何使用缓冲区和流。

我的简单情况是一个字符串变量,我想将字符串压缩或解压缩(压缩或膨胀,gzip或gunzip等)到另一个字符串。

即(我希望它如何工作)

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";

感谢您的帮助:)


阅读 304

收藏
2020-07-07

共1个答案

小编典典

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

更新2 :似乎内置的“
zlib”可能存在问题。该文档中的示例代码对我不起作用。生成的文件不可压缩(对于我来说,“文件结尾意外”失败)。另外,该模块的API并非特别适合您要尝试执行的操作。它更多地用于处理流而不是缓冲区,而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'
2020-07-07