This repository has been archived by the owner on Feb 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathserver.js
84 lines (75 loc) · 2.04 KB
/
server.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
const express = require('express')
const app = express()
const path = require('path')
const {spawn, ChildProcess} = require('child_process')
const http = require("http")
const WebSocket = require("ws")
const server = http.createServer(app);
const wss = new WebSocket.Server({server});
const VIEWS_DIR = "views"
const PUBLIC_DIR = "public"
const PORT = 8080
const SCRIPT_PATH = path.join(__dirname, 'scripts/script.py')
app.set('views', path.join(__dirname, VIEWS_DIR));
app.set('view engine', 'ejs');
app.use('/static', express.static(path.join(__dirname, PUBLIC_DIR)))
app.get('/', function (req, res) {
res.render('index')
})
app.get('/run-sync', function (req, res) {
const scriptProcess = runScript("foobar")
res.set('Content-Type', 'text/plain');
scriptProcess.stdout.pipe(res)
scriptProcess.stderr.pipe(res)
})
/**
* @param param {String}
* @return {ChildProcess}
*/
function runScript(param) {
/*
python -u script.py --foo bar
*/
return spawn('python', [
"-u", SCRIPT_PATH,
"--foo", param,
]);
}
/**
* @param id {String}
* @param ws {WebSocket}
*/
function runScriptInWebsocket(id, ws) {
const child = runScript("foobar")
child.stdout.on('data', (data) => {
ws.send(`${id}:${data}`);
});
child.stderr.on('data', (data) => {
ws.send(`${id}:error:\n${data}`);
});
child.on('close', () => {
ws.send(`${id}:done`);
});
}
// Init websocket communication
//////////////////////////////////////////////////////////////////////
let id = 1
wss.on('connection', (ws) => {
const thisId = id++;
ws.on('message', (message) => {
ws.send(`You sent -> ${message}`);
if ("run" === message) {
runScriptInWebsocket(thisId, ws)
}
});
ws.send('Connection with WebSocket server initialized');
});
// Start server
//////////////////////////////////////////////////////////////////////
server.listen(PORT, () => {
console.log('\n');
console.log('+--------------------------')
console.log(' PID %d', process.pid)
console.log(' Listening on port', PORT)
console.log('+--------------------------')
})