-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
54 lines (44 loc) · 1.31 KB
/
server.js
File metadata and controls
54 lines (44 loc) · 1.31 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
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var fs = require("fs"),
json;
var jsonPath = __dirname + '/public/comments.json';
var readJson = function (filepath, encoding){
if (typeof (encoding) == 'undefined'){
encoding = 'utf8';
}
var file = fs.readFileSync(filepath, encoding, function(err, data) {
if(err) {
return console.log("error al leer json");
}
});
return JSON.parse(file);
};
var writeJson = function(filepath, content, encoding) {
if (typeof (encoding) == 'undefined'){
encoding = 'utf8';
}
fs.writeFile(filepath, JSON.stringify(content), encoding, function(err, data) {
if(err) {
return console.log("error al guardar json");
}
console.log("json guardado: " + data);
});
};
app.use(express.static(__dirname + '/public'));
app.get('/commentsfromjson', function (req, res){
res.json(readJson(jsonPath));
});
app.post('/commentsfromjson', function (req, res) {
var json = readJson(jsonPath) || [];
console.log("json: " + json);
json.push({author: req.body.author, text: req.body.text});
writeJson(jsonPath, json);
res.json(json);
});
app.listen(5000);