-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
76 lines (67 loc) · 1.84 KB
/
server.js
File metadata and controls
76 lines (67 loc) · 1.84 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
var express = require("express");
var app = express();
var path = require("path");
var fs = require('fs');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
var idIncrementer;
fs.readFile('bookmarks.json', function read(err, data) {
if (err) {
throw err;
}
var object = JSON.parse(data);
idIncrementer = Object.keys(object).length + 1;
});
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.get('/bookmarks', function (req, res) {
var bookmarks = fs.readFile('bookmarks.json', function (err, data) {
if (err) {
console.log("error!");
}
res.send(JSON.parse(data));
});
});
app.post('/bookmarks', function (req, res) {
var bookmark = {id: idIncrementer, title : req.body.title, url : req.body.url};
var content;
fs.readFile('bookmarks.json', function (err, data) {
if (err) {
throw err;
}
content = JSON.parse(data);
content[idIncrementer] = bookmark;
idIncrementer += 1;
fs.writeFile('bookmarks.json', JSON.stringify(content), function(err) {
if (err) {
console.log("Error!");
} else {
console.log("File updated!");
}
});
});
res.send({id : bookmark.id});
});
app.delete('/bookmarks/:id', function (req, res) {
var content;
fs.readFile('bookmarks.json', function (err, data) {
if (err) {
console.log('error');
}
content = JSON.parse(data);
delete content[parseInt(req.params.id)];
fs.writeFile('bookmarks.json', JSON.stringify(content), function(err) {
if (err) {
console.log("Error!");
} else {
console.log("File deleted!");
}
});
});
res.send(null);
});
app.listen(3000);
console.log("Running at Port 3000");