-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
63 lines (55 loc) · 1.79 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
const express = require('express')
const app = express();
const { spawn } = require('child_process');
const helmet = require("helmet");
const cors = require('cors')
const PORT = process.env.PORT || 3000;
const PYTHON = process.env.PYTHON || 'python3.10';
// Define middleware
app.use(cors());
app.use(helmet());
app.use(express.json());
app.use(express.static('public'));
// Define routes
app.post('/api/search', async (req, res) => {
try {
// Get body
const idf = req.body?.idf ? "-idf" : "";
const svd = req.body?.svd ? "-svd" : "";
const k = req.body?.k ? req.body.k : 10;
const query = req.body?.query ? req.body.query : "";
const matrix_filename = `matrix${svd}${idf}`
// Run search.py and return results
const pyProg = spawn(PYTHON, ['./core/search.py', query, k, matrix_filename]);
let receivedData = ""
let errorData = "";
pyProg.stdout.on('data', (data) => {
try {
receivedData += data.toString();
} catch (error) {
res.status(500).send({ error })
}
});
pyProg.stderr.on('data', (data) => {
try {
errorData += data.toString();
} catch (error) {
res.status(500).send({ error })
}
});
pyProg.on('close', (code) => {
if (code || errorData) {
return res.status(500).send({ error: errorData })
}
res.send(JSON.parse(receivedData))
});
} catch (error) {
res.status(500).send({ error: error.message })
}
});
app.get('*', async (req, res) => {
res.sendFile(path.join(__dirname, './public/index.html'))
})
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});