-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
110 lines (82 loc) · 2.29 KB
/
lib.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import util from 'node:util';
import { fork } from 'child_process';
import { StringDecoder } from 'node:string_decoder';
import os from 'os';
const THREAD_COUNT = os.cpus().length;
export class JobQueue {
threads = THREAD_COUNT;
options = {
silent: true,
windowsHide: true,
signal: true,
timeout: 99999
};
#output = null;
#error = null;
#input = null;
#decoder = null;
constructor(list, args = [], options = {}) {
this.list = list;
this.args = args;
this.options = { ...this.options, ...options };
this.#decoder = new StringDecoder('utf8');
}
// Methods
processJob(job, thread) {
return new Promise((resolve, reject) => {
const process = fork(job, this.args, this.options);
this.#output[job] = [];
this.#error[job] = [];
this.#input[job] = [];
process.stdout?.on('data', (data) => {
this.#output[job].push(data);
});
process.stdin?.on('data', (data) => {
this.#input[job].push(data);
});
process.stderr?.on('data', (data) => {
this.#error[job].push(data);
});
process.on('spawn', () => console.info('thread: ' + thread + ' <|> ' + job + ' started.'));
process.on('error', reject);
process.on('exit', () => console.info('thread: ' + thread + ' <|> ' + job + ' finished.'));
process.on('close', resolve);
})
}
async *#getJob() {
for (let i = 0; i < this.list.length; i++) yield this.list[i];
}
async lock(thread, jobs) {
const registry = [];
for await (const job of jobs) {
registry.push(await this.processJob(job, thread));
}
return `Thread: ${thread} complete.`;
}
clear() {
return this.#output.length = 0;
}
output(convert = true) {
return this.#output.slice();
}
errors(convert = true) {
return this.#error.slice();
}
input(convert = true) {
return this.#input.slice();
}
stringify(data) {
return this.#decoder(data);
}
watch(promises) {
return Promise.allSettled(promises);
}
async run(reverse = false, clear = true) {
if (reverse) this.list.reverse();
const jobs = this.#getJob();
const thread = [];
if (clear) this.clear();
for (let i = 1; i <= this.threads; i++) thread[i] = this.lock(i, jobs);
return Promise.all(thread);
}
}