Node.js压缩与解压数据

Node.js中提供了一个很好的库Zlib来压缩解压数据。

一、压缩缓冲区

Zlib中有下面几个函数方便解压缩缓冲区.

gzip/gunzip:标准gzip压缩.

deflate/inflate:基于Huffman编码的标准deflate压缩算法。

deflateRaw/inflateRaw:针对原始缓冲区的deflate压缩算法。

它们的函数都是function(buffer,callback).


var zlib = require("zlib");
var input = '...............text...............';
zlib.deflate(input, function(err, buffer) {
  if (!err) {
    console.log("deflate (%s): ", buffer.length, buffer.toString('base64'));
    zlib.inflate(buffer, function(err, buffer) {
      if (!err) {
        console.log("inflate (%s): ", buffer.length, buffer.toString());
      }
    });
    zlib.unzip(buffer, function(err, buffer) {
      if (!err) {
        console.log("unzip deflate (%s): ", buffer.length, buffer.toString());
      }
    });
  }
});

zlib.deflateRaw(input, function(err, buffer) {
  if (!err) {
    console.log("deflateRaw (%s): ", buffer.length, buffer.toString('base64'));
    zlib.inflateRaw(buffer, function(err, buffer) {
      if (!err) {
        console.log("inflateRaw (%s): ", buffer.length, buffer.toString());
      }
    });
  }
});

zlib.gzip(input, function(err, buffer) {
  if (!err) {
    console.log("gzip (%s): ", buffer.length, buffer.toString('base64'));
    zlib.gunzip(buffer, function(err, buffer) {
      if (!err) {
        console.log("gunzip (%s): ", buffer.length, buffer.toString());
      }
    });
    zlib.unzip(buffer, function(err, buffer) {
      if (!err) {
        console.log("unzip gzip (%s): ", buffer.length, buffer.toString());
      }
    });
  }
});

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe zlib_buffers.js
deflate (18):  eJzT00MBJakVJagiegB9Zgcq
deflateRaw (12):  09NDASWpFSWoInoA
gzip (30):  H4sIAAAAAAAAC9PTQwElqRUlqCJ6AIq+x+AiAAAA
inflate (34):  ...............text...............
unzip deflate (34):  ...............text...............
inflateRaw (34):  ...............text...............
gunzip (34):  ...............text...............
unzip gzip (34):  ...............text...............

Process finished with exit code 0

二、压缩文件

可通过pipe()将压缩/解压对象从一个流输送到另一个流。


var zlib = require("zlib");
var gzip = zlib.createGzip();
var fs = require('fs');
var inFile = fs.createReadStream('zlib_file.js');
var outFile = fs.createWriteStream('zlib_file.gz');
inFile.pipe(gzip).pipe(outFile);
setTimeout(function(){
  var gunzip = zlib.createUnzip({flush: zlib.Z_FULL_FLUSH});
  var inFile = fs.createReadStream('zlib_file.gz');
  var outFile = fs.createWriteStream('zlib_file.unzipped');
  inFile.pipe(gunzip).pipe(outFile);
}, 3000);

上面代码中前面是readable流通过pipe使用压缩zlib.createGzip()然后输出到writeable中。后面的是解压的过程。


上一篇:Django 学习:为窗体加上防机器人的验证机制(验证码功能)


下一篇:Redis缓存过期策略