This repository has been archived by the owner on Sep 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 185
/
ZlibUtils.ts
61 lines (51 loc) · 1.92 KB
/
ZlibUtils.ts
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
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import zlib from "zlib";
import { Queue } from "./flowcontrol/Queue";
const queue = new Queue<any>();
let current: [string, Buffer, ZlibCallback];
export type ZlibCallback = (err: Error, result: Buffer) => void;
/**
* Serialized unzip using async zlib.unzip method. This function is a helper to
* address issues with memory fragmentation issues as documented here:
* https://nodejs.org/api/zlib.html#zlib_threadpool_usage_and_performance_considerations
*/
export function unzip(data: Buffer, cb: ZlibCallback): void {
queue.push(["unzip", data, cb]);
serialExecute();
}
/**
* Serialized inflate using async zlib.inflate method. This function is a helper to
* address issues with memory fragmentation issues as documented here:
* https://nodejs.org/api/zlib.html#zlib_threadpool_usage_and_performance_considerations
*/
export function inflate(data: Buffer, cb: ZlibCallback): void {
queue.push(["inflate", data, cb]);
serialExecute();
}
/**
* Serialized inflateRaw using async zlib.inflateRaw method. This function is a helper to
* address issues with memory fragmentation issues as documented here:
* https://nodejs.org/api/zlib.html#zlib_threadpool_usage_and_performance_considerations
*
*/
export function inflateRaw(data: Buffer, cb: ZlibCallback) {
queue.push(["inflateRaw", data, cb]);
serialExecute();
}
function serialExecute() {
// abort if already executng
if (current) return;
// remove first item and abort if nothing else to do
current = queue.shift();
if (!current) return;
// perform unzip
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
zlib[current[0]](current[1], (err: Error, res: Buffer) => {
// call supplied callback
current[2](err, res);
// reset the current status
current = undefined;
// immediate try next item
serialExecute();
});
}