-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauto.js
53 lines (45 loc) · 1.35 KB
/
auto.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
const { spawn } = require('child_process');
const moment = require('moment-timezone');
const path = require('path');
const fs = require('fs');
const scriptPath = path.join(__dirname, 'app.js');
const logFilePath = path.join(__dirname, 'error.log');
let appProcess = null;
let restartTimeout = null;
let fileWatcher = null;
const logError = (error) => {
const errorMessage = `[${moment().tz('Asia/Jakarta').format('YYYY/MM/DD hh:mm:ss')}] Error: ${error}\n`;
fs.appendFile(logFilePath, errorMessage, (err) => {
if (err) {
console.error('Gagal menulis log! Error: ', err);
}
});
};
const startApp = () => {
if (appProcess) {
appProcess.kill();
}
appProcess = spawn('node', [scriptPath], {
stdio: ['inherit', 'inherit', 'pipe']
});
appProcess.stderr.on('data', (data) => {
logError(data.toString());
});
appProcess.on('exit', (code) => {
console.log(`Aplikasi berhenti dengan kode ${code}. Restarting...`);
if (restartTimeout) {
clearTimeout(restartTimeout);
}
restartTimeout = setTimeout(startApp, 1000);
});
};
startApp();
fileWatcher = fs.watch(scriptPath, (eventType) => {
if (eventType === 'change') {
console.log(`${scriptPath} telah berubah. Restart dalam 3 detik...`);
if (restartTimeout) {
clearTimeout(restartTimeout);
}
restartTimeout = setTimeout(startApp, 3000);
}
});