-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
71 lines (62 loc) · 2.02 KB
/
Copy pathapp.js
File metadata and controls
71 lines (62 loc) · 2.02 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
"use strict";
const express = require("express");
const { exec } = require("child_process");
const { spawn } = require("child_process");
const path = require("path");
const fs = require("fs").promises;
let config;
try {
config = Object.freeze(require("./config.json"));
} catch (error) {
console.error("Error loading config.json:", error.message);
process.exit(1);
}
const app = express();
const PORT = config.serverPort;
const HOST = config.serverLocalIP;
const bitaxeName = config.bitaxeName;
const SNAPSHOT_SCRIPT_PATH = path.join(__dirname, "BPL-Snapshot.sh");
const SNAPSHOT_PNG_PATH = path.join(`/tmp/BPL/BPL-${bitaxeName}-Snapshot.png`);
const LOGGING_SCRIPT_PATH = path.join(__dirname, "BPL-Logging.sh");
// Start logging script as a detached process
const loggingScript = spawn("bash", [LOGGING_SCRIPT_PATH], {
detached: true,
stdio: ["ignore", "ignore", "ignore"],
});
loggingScript.unref();
// Handle server shutdown to terminate logging script
process.on("SIGINT", () => {
loggingScript.kill("SIGTERM");
process.exit();
});
app.get("/", async (req, res) => {
try {
// Execute snapshot script
await new Promise((resolve, reject) => {
exec(`bash ${SNAPSHOT_SCRIPT_PATH}`, (error, stdout, stderr) => {
if (error) {
console.error(`Script error: ${error.message}\nStderr: ${stderr}`);
return reject(new Error("Script execution failed"));
}
resolve();
});
});
// Check if PNG file exists
await fs.access(SNAPSHOT_PNG_PATH);
// Send the PNG file as response
res.set("Content-Type", "image/png");
res.sendFile(SNAPSHOT_PNG_PATH, (err) => {
if (err) {
console.error(`Error sending file: ${err.message}`);
res.status(500).send("Error sending PNG file");
}
});
} catch (error) {
console.error(`Error: ${error.message}`);
res.status(500).send("Server error: Failed to generate or retrieve PNG");
}
});
// Start server
app.listen(PORT, HOST, () => {
console.log(`Server running at http://${HOST}:${PORT}/`);
});