Skip to content

Commit bb183de

Browse files
authored
Create server.js
1 parent 6c2eff3 commit bb183de

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Wiki/server.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/* Node.js Backend (server.js) */
2+
const express = require('express');
3+
const fs = require('fs');
4+
const cors = require('cors');
5+
const app = express();
6+
const PORT = process.env.PORT || 3000;
7+
8+
app.use(cors());
9+
app.use(express.json());
10+
11+
// Get all wikis
12+
app.get('/api/wikis', (req, res) => {
13+
fs.readFile('./Wiki/wiki.json', 'utf8', (err, data) => {
14+
if (err) return res.status(500).send('Failed to read wiki data');
15+
res.json(JSON.parse(data));
16+
});
17+
});
18+
19+
// Add a new wiki
20+
app.post('/api/wikis', (req, res) => {
21+
const newWiki = req.body;
22+
23+
fs.readFile('./Wiki/wiki.json', 'utf8', (err, data) => {
24+
if (err) return res.status(500).send('Failed to read wiki data');
25+
const wikis = JSON.parse(data);
26+
wikis.push(newWiki);
27+
28+
fs.writeFile('./Wiki/wiki.json', JSON.stringify(wikis, null, 2), (err) => {
29+
if (err) return res.status(500).send('Failed to save wiki data');
30+
res.status(201).send('Wiki added successfully');
31+
});
32+
});
33+
});
34+
35+
// Edit a wiki
36+
app.put('/api/wikis/:title', (req, res) => {
37+
const title = req.params.title;
38+
const updatedWiki = req.body;
39+
40+
fs.readFile('./Wiki/wiki.json', 'utf8', (err, data) => {
41+
if (err) return res.status(500).send('Failed to read wiki data');
42+
let wikis = JSON.parse(data);
43+
wikis = wikis.map(w => (w.title === title ? updatedWiki : w));
44+
45+
fs.writeFile('./Wiki/wiki.json', JSON.stringify(wikis, null, 2), (err) => {
46+
if (err) return res.status(500).send('Failed to save wiki data');
47+
res.send('Wiki updated successfully');
48+
});
49+
});
50+
});
51+
52+
// Delete a wiki
53+
app.delete('/api/wikis/:title', (req, res) => {
54+
const title = req.params.title;
55+
56+
fs.readFile('./Wiki/wiki.json', 'utf8', (err, data) => {
57+
if (err) return res.status(500).send('Failed to read wiki data');
58+
const wikis = JSON.parse(data);
59+
const updatedWikis = wikis.filter(w => w.title !== title);
60+
61+
fs.writeFile('./Wiki/wiki.json', JSON.stringify(updatedWikis, null, 2), (err) => {
62+
if (err) return res.status(500).send('Failed to save wiki data');
63+
res.send('Wiki deleted successfully');
64+
});
65+
});
66+
});
67+
68+
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

0 commit comments

Comments
 (0)