Skip to content

Instantly share code, notes, and snippets.

@towc
Created February 14, 2019 11:38
Show Gist options
  • Save towc/59d4c1acb76ae5f7ef4460be9c8b6910 to your computer and use it in GitHub Desktop.
Save towc/59d4c1acb76ae5f7ef4460be9c8b6910 to your computer and use it in GitHub Desktop.
/* eslint-env browser */
/* global start, out */
const ws = new WebSocket('ws://localhost:7070');
const log = msg => out.textContent += `\n${msg}`;
const send = obj => ws.send(JSON.stringify(obj));
ws.onopen = () => log('connection established');
ws.onmessage = (msg) => {
msg = JSON.parse(msg.data);
switch (msg.type) {
case 'data':
log(msg.text);
break;
case 'status':
log(`STATUS: ${msg.text}`);
break;
case 'error':
log(`ERROR: ${msg.text}`);
break;
default:
log(`unknown message type from server: ${msg.type}`);
}
};
start.onclick = () => {
send({ type: 'start' });
};
#!/bin/bash
for run in {1..5}
do
date
sleep 1
done
<button id=start>Start</button>
<pre id=out></pre>
<script src="client.js"></script>
{
"name": "button",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.4",
"ws": "^6.1.3"
}
}
const { spawn } = require('child_process');
const cmd = './datex15.sh';
module.exports = {
setup() {
const watcher = {
ps: null,
events: {
data: [],
end: [],
},
assertEvent(event) {
if (!this.events[event]) {
throw new Error(`invalid event name, try ${Object.keys(this.events)}`);
}
},
on(event, cb) {
this.assertEvent(event);
this.events[event].push(cb);
},
send(event, data) {
this.assertEvent(event);
this.events[event].forEach(cb => cb(data));
},
// text isn't used yet, but could describe which test to run
run(text) {
const ps = spawn(cmd);
this.ps = ps;
ps.stdout.on('data', data => watcher.send('data', data.toString()));
ps.on('exit', (code) => {
watcher.send('end', code);
this.ps = null;
});
},
stop() {
if (this.ps) {
this.ps.kill();
// nulled by ps.on('exit')
}
},
};
return watcher;
},
};
const express = require('express');
const app = express();
const WebSocket = require('ws');
const script = require('./script.js');
app.use(express.static('.'));
const wss = new WebSocket.Server({ port: 7070 });
wss.on('connection', (ws) => {
const watcher = script.setup();
const send = obj => ws.send(JSON.stringify(obj));
ws.on('message', (msg) => {
msg = JSON.parse(msg);
switch (msg.type) {
case 'start':
send({ type: 'status', text: 'starting process' })
watcher.run();
break;
default:
send({ type: 'error', text: 'unknown message type' });
}
});
watcher.on('data', (line) => {
send({ type: 'data', text: line });
});
watcher.on('end', () => send({ type: 'status', text: 'ended process' }))
// this ends the process
ws.on('close', () => watcher.stop());
});
app.listen(8080, () => console.log('running on http://localhost:8080'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment