Node.js中提供了一个很好的库Zlib来压缩解压数据。
Zlib中有下面几个函数方便解压缩缓冲区.
它们的函数都是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中。后面的是解压的过程。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理