Spaces:
Sleeping
Sleeping
const express = require("express"); | |
const app = express(); | |
const bodyParser = require("body-parser"); | |
const cors = require("cors"); | |
const fs = require("fs"); | |
const { exec } = require("child_process"); | |
const compiler = require("compilex"); | |
const options = { stats: true }; | |
compiler.init(options); | |
app.use(express.json()); | |
app.use(express.urlencoded({ extended: true })); | |
app.use(cors()); | |
app.get("/", function (req, res) { | |
res.send("Hello World!!"); | |
}); | |
app.post("/compile", (req, res) => { | |
const { code, input } = req.body; // Assuming code and input are sent as POST parameters | |
// Write the Java code to Main.java file | |
fs.writeFile("/code/temp/Main.java", code, (err) => { | |
if (err) { | |
console.error(err); | |
res.status(500).send("Error writing Java file"); | |
return; | |
} | |
// Compile and run the Java code with input | |
const javaProcess = exec( | |
"javac -d /code/temp /code/temp/Main.java && java -cp /code/temp Main", | |
(error, stdout, stderr) => { | |
if (error) { | |
console.error(error); | |
res.status(500).send("Error compiling or executing Java code"); | |
return; | |
} | |
console.log(stdout); | |
console.error(stderr); | |
res.send(stdout); | |
} | |
); | |
// Pass input to the Java process | |
if (input) { | |
javaProcess.stdin.write(input); | |
javaProcess.stdin.end(); | |
} | |
}); | |
}); | |
const port = 7860; | |
app.listen(port, () => { | |
console.log(`Open http://localhost:${port}`); | |
}); | |