-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
105 lines (98 loc) · 2.67 KB
/
main.js
File metadata and controls
105 lines (98 loc) · 2.67 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
93
94
95
96
97
98
99
100
101
102
103
104
105
'use strict'
var PYTHON_SCRIPT_PATH = './files'
var http = require('http')
var child_process = require('child_process')
var fs = require('fs')
var handler = function(request, response){
console.info('connection comes')
// request.pipe(process.stdout)
if(request.url === '/sun/update' && request.method==='POST') {
var buffers = []
request.on('data', function(data){
buffers.push(data)
})
request.on('end', function(){
console.info('request end');
var body = Buffer.concat(buffers)
try {
var json = JSON.parse(body)
if(json.repository.name!=='study_python') return console.log('json.repository.name is '+json.repository.name)
response.write('now update')
process.nextTick(function(){
child_process.exec('sh ./update.sh')
})
} catch (e) {
response.write('error: ' + e.toString())
} finally {
response.end()
}
})
return
}
response.end('ok')
}
var lookForwardFiles = function(path){
return new Promise((res,rej)=>{
fs.stat(path, (err, stat)=>{
if(err) return res([])
if(!stat.isDirectory()) return res([path])
fs.readdir(path, (err, files)=>{
if(err) return res([])
var allP = files.map(f=>lookForwardFiles(path + '/' + f))
Promise.all(allP).then(data=>res([].concat.apply([],data)))
})
})
})
}
var fileListCache = []
var refreshFileListCache = function(){
console.info('do refresh filelist')
return lookForwardFiles(PYTHON_SCRIPT_PATH).then(data=>fileListCache=data)
}
refreshFileListCache()
var app = http.createServer(handler)
var io = require('socket.io')(app)
io.on('connection', socket => {
var cp
var startChildProcess = data => {
var filePath = data.path
if(cp) cp.kill()
cp = child_process.spawn('python3', [filePath])
cp.stdout.on('data', data => {
socket.emit('data', data.toString())
})
cp.stderr.on('data', (data) => {
socket.emit('cperr',data.toString())
})
cp.on('close', (code, b,c) => {
socket.emit('close', `child process exited with code ${code}`)
})
socket.emit('newcp', filePath)
}
socket.emit('data','hi')
socket.on('run', data => {
startChildProcess(data)
})
socket.on('close', data=>{
if(cp) cp.kill()
})
socket.on('command', data => {
if(cp) {
try {
cp.stdin.write(data)
} catch (e) {
socket.emit('cperr', e.toString())
} finally {
}
}
})
socket.on('refresh', data => {
var sendCache = ()=>socket.emit('refresh', fileListCache)
if(data && data.force){
refreshFileListCache().then(sendCache)
}else{
sendCache()
}
})
})
app.listen(5466)