Skip to content

Commit 3d2d078

Browse files
author
Andrew Switlyk
committed
removed comments var from global and all I/O of comments to/from disk
1 parent 6e6d46c commit 3d2d078

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

server.js

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,23 +16,26 @@ var express = require('express');
1616
var bodyParser = require('body-parser');
1717
var app = express();
1818

19-
var comments = JSON.parse(fs.readFileSync('_comments.json'));
20-
2119
app.use('/', express.static(path.join(__dirname, 'public')));
2220
app.use(bodyParser.json());
2321
app.use(bodyParser.urlencoded({extended: true}));
2422

2523
app.get('/comments.json', function(req, res) {
26-
comments = JSON.parse(fs.readFileSync('_comments.json'));
27-
res.setHeader('Content-Type', 'application/json');
28-
res.send(JSON.stringify(comments));
24+
fs.readFile('_comments.json', function(err, data) {
25+
res.setHeader('Content-Type', 'application/json');
26+
res.send(data);
27+
});
2928
});
3029

3130
app.post('/comments.json', function(req, res) {
32-
comments.push(req.body);
33-
fs.writeFile('_comments.json', JSON.stringify(comments));
34-
res.setHeader('Content-Type', 'application/json');
35-
res.send(JSON.stringify(comments));
31+
fs.readFile('_comments.json', function(err, data) {
32+
var tempComments = JSON.parse(data);
33+
tempComments.push(req.body);
34+
fs.writeFile('_comments.json', JSON.stringify(tempComments), function(err) {
35+
res.setHeader('Content-Type', 'application/json');
36+
res.send(JSON.stringify(tempComments));
37+
});
38+
});
3639
});
3740

3841
app.listen(3000);

0 commit comments

Comments
 (0)