-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
56 lines (46 loc) · 1.61 KB
/
index.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
// project imports
const { WebSocketServer } = require("ws");
const cors = require('cors');
const { metacall, metacall_load_from_file } = require('metacall')
const express = require('express')
const fs = require("fs");
// load python script
metacall_load_from_file('py', ['analysis.py'])
const app = express();
const port = 8080;
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const server = app.listen(port, () =>
console.log(`ws server is listening on ws://localhost:${port}`)
);
const wss = new WebSocketServer({ server });
wss.on("connection", (ws, req) => {
console.log("Client connected");
ws.on("error", console.error);
ws.on("message", async (message) => {
try {
const data = message.toString();
const res = metacall('process_message', data);
const imagePath = "./output/analysis_visualization.png";
fs.readFile(imagePath, (err, image) => {
if (err) {
console.error(`Error reading image: ${err.message}`);
return;
}
ws.send([image, res], (err) => {
if (err) {
console.error(`Error sending image: ${err.message}`);
} else {
console.log("Image sent successfully.");
}
});
})
} catch (error) {
ws.send(JSON.stringify({ error: "Processing failed", details: error }));
}
});
ws.on("close", () => {
console.log("Client disconnected");
});
});