-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
67 lines (53 loc) · 1.67 KB
/
server.js
File metadata and controls
67 lines (53 loc) · 1.67 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
const fs = require('fs')
const express = require('express');
const uuid = require('uuid');
const app = express();
// Choosing the port
var PORT = process.env.PORT || 3030;
// Will share any static html files with the browser
app.use( express.static('public') );
// Accept incoming POST requests
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// File that has stored note info
const dbFile = './db/db.json';
// If file exists, parse the data inside, otherwise it's an empty array
let noteList = fs.existsSync(dbFile) ?
JSON.parse( fs.readFileSync(dbFile) ) : []
// Get all saved notes
app.get('/api/notes', function(req,res) {
res.send(noteList)
});
// Post new note
app.post('/api/notes', function(req, res){
let newNote = req.body
console.log(req.body)
// Assigning random id
newNote.id = uuid.v4();
// Adding new note to the note list
noteList.push(newNote)
console.log(noteList)
// Write the new list of notes to file
fs.writeFileSync( dbFile, JSON.stringify( noteList ) )
res.send( noteList )
});
// Delete note
app.delete('/api/notes/:noteID', function(req, res){
const noteID = req.params.noteID
console.log(noteID)
// Loop through note list array to find selected note and remove it
for( let i=0; i<noteList.length; i++) {
if(noteID === noteList[i].id) {
noteList.splice(i,1)
break
}
}
// Write the new list of notes to file
fs.writeFileSync( dbFile, JSON.stringify( noteList ) )
console.log(noteList)
res.send( {message: 'Deleted Note'} )
});
// Listener
app.listen(PORT, function() {
console.log(`Serving notes on PORT ${PORT}`)
});