-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapi.js
More file actions
92 lines (80 loc) · 2.4 KB
/
Copy pathapi.js
File metadata and controls
92 lines (80 loc) · 2.4 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
87
88
89
90
91
92
const { exec, spawn } = require('child_process')
const fs = require('fs')
const kill = require('tree-kill')
const processes = {}
const options = { maxBuffer: 1024 * 1000000 }
const startServerScript = (script) => {
try {
const commandProcess = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['run', script, '--silent'])
processes[script] = commandProcess
commandProcess.stdout.on('data', (data) => {
console.log(data.toString())
})
commandProcess.stderr.on('data', (data) => {
console.log(data.toString())
})
commandProcess.on('close', (code) => {
console.log(`script ${script} exited with code ${code}`)
})
return Promise.resolve(`script ${script} is running successfully`)
} catch (error) {
return Promise.reject(error)
}
}
module.exports = {
routes: {
get: {
scripts: (req, res) => {
const appRoot = req.app.locals.appRoot
let scripts = {}
if (!fs.existsSync(`${appRoot}/package.json`)) {
return res.send({ scripts })
}
const packageJson = require(`${appRoot}/package.json`)
res.send({ scripts: packageJson.scripts })
}
},
post: {
run: (req, res) => {
const body = req.body
if (!body || !body.script) {
return res.send(false)
}
const { appRoot, config } = req.app.locals
const { serverScripts = [] } = config
if (~serverScripts.indexOf(body.script)) {
startServerScript(body.script)
.then((result) => {
res.send({ response: result, serverStarted: true })
})
.catch((error) => {
return res.status(400).send({ error: error.toString() })
})
return
}
processes[body.script] = exec(
`npm run ${body.script} --silent`,
options,
(error, response) => {
if (error !== null) {
return res.status(400).send({ error: error.toString() })
}
res.send({ response: response, serverStarted: false })
}
)
},
stop: (req, res) => {
const body = req.body
const { script } = body
if (!body || !script) {
return res.send(false)
}
if (!processes[script]) {
return res.send(false)
}
kill(processes[script].pid)
res.send(true)
}
}
}
}