-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
65 lines (54 loc) · 1.82 KB
/
server.js
File metadata and controls
65 lines (54 loc) · 1.82 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
const { response } = require('express');
const express = require('express');
const fs = require('fs');
const path = require('path');
const { isBuffer } = require('util');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
//Serve a public folder
app.use(express.static("public"));
app.listen(PORT, () => {
console.log(`Server listening on http://localhost:${PORT}`)
})
// HTML Routes
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "/public/index.html"));
});
app.get("/notes", (req, res) => {
res.sendFile(path.join(__dirname, "/public/notes.html"));
});
app.get("/api/notes", (req, res) => {
return res.sendFile(path.join(__dirname, "db/db.json"));
});
// Setup the /api/notes POST route
app.post("/api/notes", function (req, res) {
fs.readFile("./db/db.json", "utf-8", function (err, notedata) {
let savedNotes = JSON.parse(notedata);
console.log(savedNotes)
let newNote = req.body;
newNote.id = savedNotes.length + 1;
savedNotes.push(newNote)
fs.writeFile("./db/db.json", JSON.stringify(savedNotes), "utf-8", function (err) {
if (err) throw err;
console.log('Saved!')
})
})
res.send("Done")
})
// DELETE NOTE
app.delete("/api/notes/:id", function (req, res) {
var id = req.params.id
fs.readFile("./db/db.json", "utf-8", function (error, data) {
if (error) throw error;
let savedNote = JSON.parse(data)
let deleteNote = savedNote.findIndex((x) => x.id == id)
savedNote.splice(deleteNote, 1)
fs.writeFile("./db/db.json", JSON.stringify(savedNote), "utf-8", function (error) {
if (error) throw error;
console.log("Deleted!")
})
})
res.send("Done!")
})