This repository has been archived by the owner on Aug 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.js
116 lines (101 loc) · 2.42 KB
/
service.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
111
112
113
114
115
116
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');
class Service {
constructor(name) {
this.name = name;
}
async run() {
throw new Error('Not implemented');
}
kill() {
throw new Error('Not implemented');
}
}
class SpawnService extends Service {
/**
*
* @param {String} name
* @param {String} cwd
* @param {String} program
* @param {Array.<String>} args
* @param {Object} envVar
* @param {?String} logDir
*/
constructor(name, cwd, program, args, envVar, logDir) {
super(name);
this.cwd = cwd;
this.program = program;
this.args = args;
this.envVar = envVar;
this.logDir = logDir;
/**
* @type {?ChildProcess}
*/
this.process = null;
}
/**
* @override
* @returns {Promise<void>}
*/
async run() {
let env = Object.create(process.env);
let cwd = process.cwd();
Object.assign(env, this.envVar);
process.chdir(this.cwd);
this.process = spawn(this.program, this.args, {env});
process.chdir(cwd);
if(this.logDir) {
let dir = path.join(cwd, this.logDir);
try {
// TODO maybe async?
fs.mkdirSync(dir);
} catch(e) {
}
let logAddress = path.join(dir, `${this.name}.doogh.log`);
let logFile = fs.createWriteStream(logAddress);
this.process.stdout.pipe(logFile);
this.process.stderr.pipe(logFile);
}
//Promise.delay(1000);
}
/**
* @override
*/
kill() {
this.process.kill();
}
}
class JsService extends SpawnService {
/**
*
* @param {String} name
* @param {String} cwd
* @param {String} script
* @param {Array.<String>} args
* @param {Object} envVar
* @param {?String} logDir
*/
constructor(name, cwd, script, args, envVar, logDir) {
super(name, cwd, 'node', [script, ...args], envVar, logDir);
}
}
class PyService extends SpawnService {
/**
*
* @param {String} name
* @param {String} cwd
* @param {String} moduleName
* @param {Array.<String>} args
* @param {Object} envVar
* @param {String} executable
* @param {?String} logDir
*/
constructor(name, cwd, moduleName, args, envVar, executable = 'python', logDir = './logs') {
super(name, cwd, executable, ['-m', moduleName, ...args], envVar, logDir);
}
}
module.exports.Service = Service;
module.exports.SpawnService = SpawnService;
module.exports.JsService = JsService;
module.exports.PyService = PyService;