# 十三.compress

# 1.压缩与解压缩处理

可以使用zlib模块进行压缩与解压缩处理,压缩文件以后可以减少体积,加快传输速度和节约宽带

# 2.压缩对象

压缩和解压缩对象都是一个可读可写流

方法 说明
zlib.createGzip 返回 Gzip 流对象,使用 Gzip 算法对数据进行压缩处理
zlib.createGunzip 返回 Gzip 流对象,使用 Gzip 算法对压缩的数据进行解压缩处理
zlib.createDeflate 返回 Deflate 流对象,使用 Deflate 算法对数据进行压缩处理
zlib.createInflate 返回 Deflate 流对象,使用 Deflate 算法对数据进行解压缩处理

# 3.压缩与解压缩

var zlib = require("zlib")
var fs = require("fs")

function zip(src) {
  var gzip = zlib.createGzip() //创建压缩流
  var inputStream = fs.createReadStream(src)
  var outputStream = fs.createWriteStream(src + ".gz")
  inputStream.pipe(gzip).pipe(outputStream)
}
zip("source.txt")

function unzip(src) {
  var gunzip = zlib.createGunzip()
  var inputStream = fs.createReadStream(src)
  var outputStream = fs.createWriteStream(src.slice(0, -3))
  inputStream.pipe(gunzip).pipe(outputStream)
}
gnzip("source.txt.gz")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 4.在 http 中的应用

var zlib = require("zlib")
var fs = require("fs")
var http = require("http")
http.createServer(function(request, response) {
  var raw = fs.createReadStream("." + request.url)
  var acceptEncoding = request.headers["accept-encoding"]
  if (!acceptEncoding) {
    acceptEncoding = ""
  }
  if (acceptEncoding.match(/\bdeflatte\b/)) {
    response.setHeader("Content-Encoding", "deflate")
    raw.pipe(zlib.createDeflate()).pipe(response)
  } else if (acceptEncoding.match(/\bgzip\b/)) {
    response.setHeader("Content-Encoding", "gzip")
    raw.pipe(zlib.createGzip()).pipe(response)
  } else {
    raw.pipe(response)
  }
}).listen(9090)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var zlib = require('zlib')
var fs = require('fs')
var http = require('http')

var request = http.get({
  host: 'localhost',
  path: '/index.html',
  port: 9090,
  headers: {
    'accept-encoding':'gzip,deflate'
  }
})

request.on('response',function(response){
  var output = fs.createWriteStream('test.txt')
  switch(response.headers['content-encoding']){
    case 'gzip':
      response.pipe(zlib.createGunzip()).pipe(output)
      break;
    case 'deflate':
      response.pipe(zlib.createInflate()).pipe(output)}
      break;
    default:
      response.pipe(output)
      break;
})
request.end()
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
26
27

# 5.方法调用

var zlib = require("zlib")
var fs = require("fs")

var out = fs.createWriteStream("input.log")
var input = "input"
zlib.gzip(input, function(err, buffer) {
  if (!err) {
    zlib.unzip(buffer, function(err, buffer) {
      if (!err) {
        console.log(buffer.toString())
        out.end(buffer)
      }
    })
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15