-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
57 lines (49 loc) · 1.54 KB
/
server.js
File metadata and controls
57 lines (49 loc) · 1.54 KB
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
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const cors = require('cors');
const app = express();
const PORT = 3100;
const POSTS_FILE = 'posts.json';
app.use(cors());
app.use(bodyParser.json());
// Load comments from file
let comments = [];
function loadComments() {
try {
const data = fs.readFileSync(POSTS_FILE, 'utf8');
comments = JSON.parse(data);
} catch (error) {
console.error('Error reading comments file:', error);
comments = [];
}
}
// Save comments to file
function saveComments() {
try {
fs.writeFileSync(POSTS_FILE, JSON.stringify(comments, null, 2), 'utf8');
} catch (error) {
console.error('Error writing to comments file:', error);
}
}
// Initialize comments from the file
loadComments();
// Endpoint to get all comments
// Endpoint to get all comments in descending order
app.get('/comments', (req, res) => {
res.json(comments.slice().reverse()); // Reverse a copy of the comments array
});
// Endpoint to post a new comment
app.post('/comments', (req, res) => {
const newComment = req.body;
if (!newComment.username || !newComment.text) {
return res.status(400).json({ error: 'Username and text are required' });
}
comments.push(newComment);
saveComments(); // Save updated comments to file
res.status(201).json({ message: 'Comment added successfully' });
});
// Start the server
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on http://0.0.0.0:${PORT}`);
});