-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
90 lines (65 loc) · 2.24 KB
/
server.js
File metadata and controls
90 lines (65 loc) · 2.24 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
exports.app = app;
const PORT = process.env.PORT || 4000;
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(express.static('public'));
app.get('/notes', (req, res) =>
{res.sendFile(path.join(__dirname, '/public/notes.html'))
});
app.get('/',(req, res) =>
{res.sendFile(path.join(__dirname, '/public/index.html'))
});
app.get('/api/notes', (req, res) =>
// return res.json(notes);
{fs.readFile('db/db.json', (err, data) => {
if (err) throw err;
let notes = JSON.parse(data);
return res.json(notes);
});
});
app.listen(PORT, () =>
{console.log(`app listening at http://localhost:${PORT}`)
});
app.post('/api/notes', (req, res) => {
let newNote = req.body;
console.log(newNote);
fs.readFile('db/db.json', function(err, data){
if (err) throw err;
let notes = JSON.parse(data);
newNote.id = notes.length + 1;
//in that, parse data you get back
//let Notearray = array.length-1
//array.length-1
// newNote.id += 1
//push newNote into Notearray
notes.push(newNote)
//writeFile("db/db.json", JSON.stringify(newNote), function(err){})
fs.writeFile('db/db.json', JSON.stringify(notes), function(err){
if (err) throw err;
return res.json(notes)
console.log("saved into db.json")
});
});
}
);
app.delete('/api/notes/:id', function(req, res){
fs.readFile('db/db.json',function(err, data){
if (err) throw err;
let notes = JSON.parse(data);
let id = req.params.id;
let newNotes = notes.filter(note => note.id != id);
for (i = 0; i < newNotes.length; i++){
newNotes[i].id = i + 1;
}
console.log(newNotes)
fs.writeFile('db/db.json', JSON.stringify(newNotes), function(err){
if (err) throw err;
return res.status(202).send();
console.log('saved into db.json')
});
});
});