-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (58 loc) · 2 KB
/
server.js
File metadata and controls
71 lines (58 loc) · 2 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
58
59
60
61
62
63
64
65
66
67
68
69
70
// Require dependencies
const express = require("express");
const path = require("path");
const fs = require("fs");
// Initialize Express package
const app = express();
const PORT = process.env.PORT || 8081;
const mainDir = path.join(__dirname, "/public");
// Set up data parsing
app.use(express.static('public'));
app.use(express.urlencoded({extended: true}));
app.use(express.json());
// ROUTES TO HTML AND API DATA
app.get("/notes", function(req, res) {
res.sendFile(path.join(mainDir, "notes.html"));
});
app.get("/api/notes", function(req, res) {
res.sendFile(path.join(__dirname, "/db/db.json"));
});
app.get("/api/notes/:id", function(req, res) {
let savedNotes = JSON.parse(fs.readFileSync("./db/db.json", "utf8"));
res.json(savedNotes[Number(req.params.id)]);
});
app.get("*", function(req, res) {
res.sendFile(path.join(mainDir, "index.html"));
});
app.post("/api/notes", function(req, res) {
let savedNotes = JSON.parse(fs.readFileSync("./db/db.json", "utf8"));
let newNote = req.body;
let uniqueID = (savedNotes.length).toString();
newNote.id = uniqueID;
savedNotes.push(newNote);
fs.writeFileSync("./db/db.json", JSON.stringify(savedNotes));
console.log("Note saved to db.json. Content: ", newNote);
res.json(savedNotes);
})
// Delete note function
app.delete("/api/notes/:id", function(req, res) {
let savedNotes = JSON.parse(fs.readFileSync("./db/db.json", "utf8"));
let noteID = req.params.id;
let newID = 0;
console.log(`Deleting note with ID ${noteID}`);
savedNotes = savedNotes.filter(currNote => {
return currNote.id != noteID;
})
for (currNote of savedNotes) {
currNote.id = newID.toString();
newID++;
}
// Write new notes to db.json file
fs.writeFileSync("./db/db.json", JSON.stringify(savedNotes));
res.json(savedNotes);
})
// LISTENER
// The below code effectively "starts" our server
app.listen(PORT, function () {
console.log(`Server listening on: http://localhost:${PORT}`);
});