-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExpress.js
55 lines (47 loc) · 1.57 KB
/
Express.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
const express = require('express');
const cors = require('cors');
const fs = require('fs').promises;
const path = require('path');
const app = express();
app.use(cors());
app.use(express.json());
const resultsFile = path.join(__dirname, 'results.json');
app.post('/save-results', async (req, res) => {
try {
const result = req.body;
let results = [];
try {
const data = await fs.readFile(resultsFile, 'utf8');
results = JSON.parse(data);
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}
results.push(result);
await fs.writeFile(resultsFile, JSON.stringify(results, null, 2));
res.json({ message: 'Results saved successfully' });
} catch (error) {
console.error('Error saving results:', error);
res.status(500).json({ error: 'Failed to save results' });
}
});
app.get('/get-results', async (req, res) => {
try {
const data = await fs.readFile(resultsFile, 'utf8');
const results = JSON.parse(data);
res.json(results);
} catch (error) {
if (error.code === 'ENOENT') {
res.json([]);
} else {
console.error('Error reading results:', error);
res.status(500).json({ error: 'Failed to read results' });
}
}
});
app.use(express.static(__dirname));
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});