-
Notifications
You must be signed in to change notification settings - Fork 1
/
zlibutil.coffee
72 lines (57 loc) · 1.77 KB
/
zlibutil.coffee
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
zlib = require('zlib')
util = require('util')
Iconv = require('iconv').Iconv
class ZlibUtil
constructor: () ->
@gbk_to_utf8 = new Iconv('GBK//TRANSLIT//IGNORE','UTF-8//TRANSLIT//IGNORE')
@utf8_to_gbk = new Iconv('UTF-8//TRANSLIT//IGNORE','GBK//TRANSLIT//IGNORE')
compress_type: (content_encoding) ->
# Compress data using gzip.
gzip = 'gzip'
# Compress data using deflate
deflate = 'deflate'
# Compress data using deflate, and do not append a zlib header
deflateRaw = 'deflateRaw'
if content_encoding.match(/.*(gzip).*/)?
return gzip
else if content_encoding.match(/.*(deflate).*/)?
return deflate
else if content_encoding.match(/.*(deflateRaw).*/)?
return deflateRaw
else
return null
compress: (content_type, content_encoding, str, callback) ->
if content_type.match(/.*(gbk|GBK).*/)?
buf = @utf8_to_gbk.convert(str)
else
buf = new Buffer(str)
type = @compress_type(content_encoding)
if type?
zlib["#{type}"] buf, (err, cbuf) ->
callback(cbuf)
else
callback(buf)
decompress_type: (content_encoding) ->
# Decompress a gzip stream.
gunzip = 'gunzip'
# Decompress a deflate stream
inflate = 'inflate'
# Decompress a raw deflate stream
inflateRaw = 'inflateRaw'
if content_encoding.match(/.*(gzip).*/)?
return gunzip
else if content_encoding.match(/.*(deflate).*/)?
return inflate
else if content_encoding.match(/.*(deflateRaw).*/)?
return inflateRaw
else
return null
decompress: (content_type, content_encoding, buffer, callback) ->
type = @decompress_type(content_encoding)
zlib[type] buffer, (err, decbuf) ->
if content_type.match(/.*(gbk|GBK).*/)?
str = @gbk_to_utf8.convert(decbuf).toString()
else
str = decbuf.toString()
callback(str)
module.exports = new ZlibUtil()