-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathutils.ts
More file actions
77 lines (74 loc) · 2.39 KB
/
Copy pathutils.ts
File metadata and controls
77 lines (74 loc) · 2.39 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
import path from "path";
import { once, Readable } from "stream";
import { Worker } from "worker_threads";
import { IEmitter, EmitterEvents, EventEmitter } from "@models/emitter";
import {
FilePath,
ListStreamOptions,
READABLE_STREAM_ALERT,
ReferenceKey,
StreamEvent,
StreamListener,
} from "@models/stream";
import { NodeWorkerMessage, WorkerEvent } from "@models/worker";
import { generateStream } from "..";
async function getArrayFromStream<T>(
stream: Readable,
showWarnings: boolean = true,
): Promise<T[]> {
if (showWarnings) {
console.warn(READABLE_STREAM_ALERT);
}
const data: T[] = [];
stream.on(StreamEvent.Data, (chunk) => data.push(chunk));
await once(stream, "end");
return data;
}
export async function generateWorker<T extends Record<string, unknown>>(
prevList: Readable | FilePath | T[],
nextList: Readable | FilePath | T[],
referenceKey: ReferenceKey<T>,
options: ListStreamOptions,
emitter: IEmitter<T>,
) {
try {
if (prevList instanceof Readable) {
prevList = await getArrayFromStream(prevList, options?.showWarnings);
}
if (nextList instanceof Readable) {
nextList = await getArrayFromStream(nextList, options?.showWarnings);
}
const worker = new Worker(path.resolve(__dirname, "./node-worker.cjs"));
worker.postMessage({ prevList, nextList, referenceKey, options });
worker.on(WorkerEvent.Message, (e: NodeWorkerMessage<T>) => {
const { event, chunk, error } = e;
if (event === StreamEvent.Data) {
emitter.emit(StreamEvent.Data, chunk);
} else if (event === StreamEvent.Finish) {
emitter.emit(StreamEvent.Finish);
worker.terminate();
} else if (event === StreamEvent.Error) {
emitter.emit(StreamEvent.Error, new Error(error));
worker.terminate();
}
});
worker.on(WorkerEvent.Error, (err: Error) =>
emitter.emit(StreamEvent.Error, new Error(err.message)),
);
} catch (err) {
return emitter.emit(StreamEvent.Error, err as Error);
}
}
export function workerDiff<T extends Record<string, unknown>>(
prevList: FilePath | T[],
nextList: FilePath | T[],
referenceKey: ReferenceKey<T>,
options: ListStreamOptions,
): StreamListener<T> {
const emitter = new EventEmitter<EmitterEvents<T>>();
setTimeout(
() => generateStream(prevList, nextList, referenceKey, options, emitter),
0,
);
return emitter as StreamListener<T>;
}