-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathstream.utils.ts
More file actions
94 lines (74 loc) · 2.19 KB
/
Copy pathstream.utils.ts
File metadata and controls
94 lines (74 loc) · 2.19 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { ReadStream, WriteStream } from 'node:fs';
import { Transform, TransformCallback, TransformOptions } from 'node:stream';
export class StreamUtils {
static readStreamToReadableStream(readStream: ReadStream): ReadableStream<Uint8Array> {
const readable = new ReadableStream<Uint8Array>({
async start(controller) {
readStream.on('data', (chunk) => {
controller.enqueue(Buffer.from(chunk));
});
readStream.on('end', () => {
controller.close();
});
},
});
return readable;
}
static writeStreamToWritableStream(writeStream: WriteStream): WritableStream<Uint8Array> {
const writable = new WritableStream<Uint8Array>({
write(chunk) {
writeStream.write(chunk);
},
});
return writable;
}
static joinReadableBinaryStreams(streams: ReadableStream<Uint8Array>[]): ReadableStream<Uint8Array> {
const streamsCopy = streams.map((s) => s);
let keepReading = true;
const flush = () => streamsCopy.forEach((s) => s.cancel());
const stream = new ReadableStream({
async pull(controller) {
if (!keepReading) return flush();
const downStream = streamsCopy.shift();
if (!downStream) {
return controller.close();
}
const reader = downStream.getReader();
let done = false;
while (!done && keepReading) {
const status = await reader.read();
if (!status.done) {
controller.enqueue(status.value);
}
done = status.done;
}
reader.releaseLock();
},
cancel() {
keepReading = false;
},
});
return stream;
}
}
export class BufferStream extends Transform {
private chunks: Buffer[];
constructor(opts?: TransformOptions) {
super(opts);
this.chunks = [];
}
_transform(chunk: Buffer, _: BufferEncoding, callback: TransformCallback) {
this.chunks.push(chunk);
callback(null, chunk);
}
_flush(callback: TransformCallback) {
callback();
}
reset() {
this.chunks = [];
}
getBuffer(): Buffer | undefined {
if (this.chunks.length === 0) return undefined;
return Buffer.concat(this.chunks);
}
}