gzip
# Node.js
const zlib = require("zlib");
const data = Buffer.from("hello world", "utf-8");
zlib.gzip(data, (err, compressed) => {
if (err) {
console.error(err);
}
console.log(compressed);
zlib.unzip(compressed, (err, decompressed) => {
if (err) {
console.error(err);
}
console.log(decompressed.toString());
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Output
<Buffer 1f 8b 08 00 00 00 00 00 00 13 cb 48 cd c9 c9 57 28 cf 2f ca 49 01 00 85 11 4a 0d 0b 00 00 00>
hello world
1
2
2
# Go
package main
import (
"bytes"
"compress/gzip"
"fmt"
)
func main() {
data := []byte("hello world")
compressed := new(bytes.Buffer)
w := gzip.NewWriter(compressed)
if _, err := w.Write(data); err != nil {
panic(err)
}
if err := w.Close(); err != nil {
panic(err)
}
fmt.Println(compressed.Bytes())
decompressed := new(bytes.Buffer)
r, err := gzip.NewReader(compressed)
if err != nil {
panic(err)
}
_, err = decompressed.ReadFrom(r)
if err != nil {
panic(err)
}
fmt.Println(string(decompressed.Bytes()))
}
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
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
Output
[31 139 8 0 0 0 0 0 0 255 202 72 205 201 201 87 40 207 47 202 73 1 4 0 0 255 255 133 17 74 13 11 0 0 0]
hello world
1
2
2
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22