-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
86 lines (77 loc) · 2.19 KB
/
server.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser');
const fs = require('fs');
app.use(bodyParser.urlencoded({
extended: true
}))
function createFile(filename) {
fs.open(filename, 'r', function (err, fd) {
if (err) {
fs.writeFile(filename, '', function (err) {
if (err) {
console.log(err);
}
console.log("The file was saved!");
});
} else {
console.log("The file exists!");
}
});
}
const {
exec,
spawn
} = require("child_process");
const {
log
} = require('console');
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('index');
});
app.post('/runcode', (req, res) => {
try {
dir = './cpp/';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, {
recursive: true
});
}
fs.writeFile("./cpp/test.cpp", req.body.code, function (err) {
if (err) {
console.log(err);
} else {
// console.log("The file was saved!");
}
});
exec("g++ -o ./cpp/a.out ./cpp/test.cpp", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
error.message = error.message.split('./cpp/').join('');
var lines = error.message.split('\n');
lines.splice(0, 1);
var newtext = lines.join('\n');
res.send(newtext);
} else {
const child = spawn("./cpp/a.out");
child.stdin.write(req.body.stdin)
child.stdin.end();
child.stdout.on("data", (data) => {
res.send(data);
});
child.stdout.on('error', function (err) {
if (err.code == "EPIPE") {
child.exit(0);
}
});
}
});
} catch (error) {
console.log(error);
}
});
app.listen(port, () => {
console.log(`App listening on port http://localhost:${port}`)
});