-
Notifications
You must be signed in to change notification settings - Fork 4
/
daemon.js
61 lines (58 loc) · 1.33 KB
/
daemon.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
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const {spawn} = require('child_process')
const kill = require('tree-kill')
const minimisted = require('minimisted')
module.exports = function (cmdName, target) {
const args = [
target
]
async function main({_: [cmd]}) {
switch (cmd) {
case 'start': {
require('daemonize-process')()
let server = spawn(
'node', args,
{
stdio: 'inherit',
windowsHide: true,
}
)
fs.writeFileSync(
path.join(process.cwd(), `${cmdName}.pid`),
String(process.pid),
'utf8'
)
process.on('exit', server.kill)
return
}
case 'stop': {
let pid
try {
pid = fs.readFileSync(
path.join(process.cwd(), `${cmdName}.pid`),
'utf8'
);
} catch (err) {
console.log(`No ${cmdName}.pid file`)
return
}
pid = parseInt(pid)
console.log('killing', pid)
kill(pid, (err) => {
if (err) {
console.log(err)
} else {
fs.unlinkSync(path.join(process.cwd(), `${cmdName}.pid`))
}
})
return
}
default: {
require(target)
}
}
}
minimisted(main)
}