-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (56 loc) · 1.92 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const express = require("express");
const cors = require("cors");
const { v4 } = require("uuid");
const fs = require("fs");
const { runCode } = require("./runCode");
const app = express();
app.use(express.json());
app.use(cors());
app.get("/hello", (req, res) => {
res.send("HELLO FROM JAVA");
});
function writeCodeToFile(code) {
const dirName = "/home/app/javaFiles/temp_" + Date.now();
const className = "Main";
fs.mkdirSync(dirName);
const path = `${dirName}/${className}.java`;
fs.writeFileSync(path, code);
return { dirName, className };
}
function injectTheMainFunctionCode(code, command) {
const mainPattern = /main/;
code = code.replace(mainPattern, "dummyFunc");
const index = code.indexOf("public static void dummyFunc(String[] Args)");
code = [code.slice(0, index), command, code.slice(index)].join("");
return code;
}
app.post("/java/playground", (req, res) => {
const { code } = req.body;
let result;
const { dirName, className } = writeCodeToFile(code);
try {
const { stderr, stdout, executeTime } = runCode(dirName, className);
stdout && (result = { status: "success", result: stdout, executeTime });
stderr && (result = { status: "error", result: stderr, executeTime });
res.json(result);
} catch (err) {
console.log(`Exception occurred!!!`, err);
}
});
app.post("/java/test", (req, res) => {
const { code, command } = req.body;
const newCode = injectTheMainFunctionCode(code, command);
const { dirName, className } = writeCodeToFile(newCode);
let result;
try {
const { stderr, stdout, executeTime } = runCode(dirName, className);
stdout && (result = { status: "success", result: stdout, executeTime });
stderr && (result = { status: "error", result: stderr, executeTime });
res.json(result);
} catch (err) {
console.log(`Exception occurred!!!`, err);
}
});
app.listen(6002, () => {
console.log("Java mini server listen from 6002");
});