-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
68 lines (55 loc) · 1.76 KB
/
app.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
const express = require('express');
const bodyParser = require('body-parser');
const { spawn } = require('child_process');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const executePython = async (script, args) => {
const arguments = args.map(arg => arg.toString());
const py = spawn("python", [script, ...arguments]);
const result = await new Promise((resolve, reject) => {
let output;
// Get output from python script
py.stdout.on('data', (data) => {
output = JSON.parse(data);
});
// Handle erros
py.stderr.on("data", (data) => {
console.error(`[python] Error occured: ${data}`);
reject(`Error occured in ${script}`);
});
py.on("exit", (code) => {
console.log(`Child process exited with code ${code}`);
resolve(output);
});
});
return result;
}
app.get('/', async (req, res) => {
res.render('index', {result: null});
});
app.post('/', async (req, res) => {
const word = req.body.word;
let result = null;
if (!word) {
result = {
"Best Algorithm": ("0 s"),
"Corrections": {"word": "No word provided"},
"Time": ("0 s")
}
res.render('index',{ result: result });
}
try {
result = await executePython('python/b.py', [word]);
if(result.Corrections.word === undefined ) {
result.Corrections.word = "Word is true!";
}
res.render('index',{ result: result });
} catch (error) {
res.status(500).json({ error: error});
}
});
app.listen(5000, () => {
console.log('[server] Application started!')
});