-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathindex.js
More file actions
86 lines (72 loc) · 1.66 KB
/
index.js
File metadata and controls
86 lines (72 loc) · 1.66 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
console.log('Starting...');
import { Worker } from 'worker_threads';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { watchFile, unwatchFile } from 'fs';
import readline from 'readline';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rl = readline.createInterface(process.stdin, process.stdout);
let worker = null;
let running = false;
let restartTimer = null;
function start(file) {
if (running) return;
running = true;
const full = join(__dirname, file);
if (worker) worker.terminate();
worker = new Worker(full);
if (restartTimer) {
clearTimeout(restartTimer);
restartTimer = null;
}
worker.on('message', (msg) => {
console.log('[MESSAGE]', msg);
if (msg === 'restart' || msg === 'reset') {
restart();
}
});
worker.on('exit', (code) => {
console.log('❗ Worker exited with code', code);
running = false;
if (code !== 0) {
restartTimer = setTimeout(
() => {
console.log('⏳ Auto restart...');
restart();
},
30 * 60 * 1000
);
}
watchFile(full, () => {
unwatchFile(full);
console.log('♻️ File updated → Restarting...');
start(file);
});
});
if (!rl.listenerCount('line')) {
rl.on('line', (line) => {
const cmd = line.trim().toLowerCase();
if (!cmd) return;
if (cmd === 'exit') {
console.log('⛔ Exiting...');
worker?.terminate();
process.exit(0);
}
if (cmd === 'restart' || cmd === 'reset') {
console.log('Restart...');
restart();
}
worker?.postMessage(cmd);
});
}
}
function restart() {
if (worker) {
try {
worker.terminate();
} catch {}
}
running = false;
start('main.js');
}
start('main.js');