forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfinished.js
46 lines (44 loc) · 1.34 KB
/
finished.js
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
// @ts-check
module.exports = finished;
/**
* @param {NodeJS.ReadableStream | NodeJS.WritableStream} stream
* @returns {Promise<void>}
*/
function finished(stream) {
return new Promise((resolve, reject) => {
const readable = "readable" in stream && stream.readable;
const writable = "writable" in stream && stream.writable;
let countdown = 0;
const cleanup = () => {
if (readable) stream.removeListener("end", signal);
if (writable) stream.removeListener("finish", signal);
stream.removeListener("error", onerror);
};
const signal = () => {
if (countdown > 0) {
countdown--;
if (countdown === 0) {
cleanup();
resolve();
}
}
};
const onerror = (error) => {
if (countdown > 0) {
countdown = 0;
cleanup();
reject(error);
}
};
stream.once("error", onerror);
if (readable) {
countdown++;
stream.once("end", signal);
}
if (writable) {
countdown++;
stream.once("finish", signal);
}
if (countdown === 0) signal();
});
}