One-For-All-Server / index.js
hprasath's picture
Update index.js
bc37f26 verified
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!!");
});
const TIMEOUT_VALUE = 10000;
app.post("/compile", function (req, res) {
var code = req.body.code;
var input = req.body.input;
var lang = req.body.lang;
try {
if (lang == "Python") {
if (!input) {
var envData = { OS: "linux" };
compiler.compilePython(envData, code, function (data) {
if (data.output) {
res.send(data);
} else {
res.send({ error: data.error });
}
});
} else {
var envData = { OS: "linux" };
compiler.compilePythonWithInput(envData, code, input, function (data) {
if (data.output) {
res.send(data);
} else {
res.send({ error: data.error });
}
});
}
}else if(lang == "Java"){
fs.writeFile("/code/temp/Main.java", code, (err) => {
if (err) {
console.error(err);
res.status(500).send("Error writing Java file");
return;
}
const javaProcess = exec(
"javac -d /code/temp /code/temp/Main.java && java -cp /code/temp Main",
{ timeout: TIMEOUT_VALUE }, // Add timeout option
(error, stdout, stderr) => {
if (error) {
console.error(error);
res.send({ error: error.message });
return;
}
console.error(stderr);
res.send({output:stdout});
}
);
if (input) {
javaProcess.stdin.write(input);
javaProcess.stdin.end();
}
});
}
else if (lang == "Cpp") {
fs.writeFile("/code/temp/Main.cpp", code, (err) => {
if (err) {
console.error(err);
res.status(500).send("Error writing C++ file");
return;
}
const cppProcess = exec(
"g++ -o /code/temp/Main /code/temp/Main.cpp && /code/temp/Main",
{ timeout: TIMEOUT_VALUE }, // Add timeout option
(error, stdout, stderr) => {
if (error) {
console.error(error);
res.send({ error: error.message });
return;
}
console.error(stderr);
res.send({ output: stdout });
}
);
if (input) {
cppProcess.stdin.write(input);
cppProcess.stdin.end();
}
});
}
} catch (e) {
console.log("error:" + e);
}
});
const port = 7860;
app.listen(port, () => {
console.log(`Open http://localhost:${port}`);
});