@@ -16,22 +16,26 @@ var express = require('express');
16
16
var bodyParser = require ( 'body-parser' ) ;
17
17
var app = express ( ) ;
18
18
19
- var comments = JSON . parse ( fs . readFileSync ( '_comments.json' ) ) ;
20
-
21
19
app . use ( '/' , express . static ( path . join ( __dirname , 'public' ) ) ) ;
22
20
app . use ( bodyParser . json ( ) ) ;
23
21
app . use ( bodyParser . urlencoded ( { extended : true } ) ) ;
24
22
25
23
app . get ( '/comments.json' , function ( req , res ) {
26
- res . setHeader ( 'Content-Type' , 'application/json' ) ;
27
- 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
+ } ) ;
28
28
} ) ;
29
29
30
30
app . post ( '/comments.json' , function ( req , res ) {
31
- comments . push ( req . body ) ;
32
- fs . writeFile ( '_comments.json' , JSON . stringify ( comments ) )
33
- res . setHeader ( 'Content-Type' , 'application/json' ) ;
34
- 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
+ } ) ;
35
39
} ) ;
36
40
37
41
app . listen ( 3000 ) ;
0 commit comments