-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathapp.js
More file actions
94 lines (72 loc) · 2.01 KB
/
app.js
File metadata and controls
94 lines (72 loc) · 2.01 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
'use strict';
const express = require('express');
const WebSocketServer = require('ws').Server;
const server = require('http').createServer();
const exec = require('child_process').exec;
const wss = new WebSocketServer({ server: server });
const app = express();
const PORT = 3001;
/** ROUTES **/
app.use('/static', express.static('static'));
app.get('/', function(req, res) {
res.sendFile('index.html', {root: __dirname});
});
app.get('/load', function(req, res) {
res.sendFile('load.html', {root: __dirname});
});
app.get('/cats', function(req, res) {
res.sendFile('cats.html', {root: __dirname});
});
// Example of a slow request
app.get('/slowfile', function(req, res) {
setTimeout(() => {
res.sendFile('index.html', {root: __dirname});
}, 6 * 1000);
});
/** END ROUTES **/
let pushDataInterval;
wss.on('connection', function connection(ws) {
console.log('clients connected: ', wss.clients.size);
if (!pushDataInterval) {
pushDataInterval = getServerLoad();
}
if (ws.readyState === ws.OPEN) {
ws.send('welcome!');
}
ws.on('close', function close() {
if (wss.clients.size === 0) {
clearInterval(pushDataInterval);
pushDataInterval = null;
}
console.log('disconnected');
});
ws.on('error', function error() {
console.log('error');
});
});
/**
* Run shell script on an interval and broadcast to connected clients.
* @return {Object} The interval object
*/
function getServerLoad() {
return setInterval(() => {
// Execute bash script
const loadScript = exec(`./proc.sh`);
loadScript.stdout.on('data', function(data) {
wss.broadcast(JSON.stringify({name: 'load', data}));
});
}, 2 * 1000);
}
/**
* Broadcast data to all connected clients
* @param {Object} data
* @void
*/
wss.broadcast = function broadcast(data) {
console.log('Broadcasting: ', data);
wss.clients.forEach(function each(client) {
client.send(data);
});
};
server.on('request', app);
server.listen(PORT, function () { console.log('Listening on ' + PORT); });