File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Create web server
2
+
3
+ // Import modules
4
+ const express = require ( 'express' ) ;
5
+ const bodyParser = require ( 'body-parser' ) ;
6
+ const fs = require ( 'fs' ) ;
7
+
8
+ // Create web server
9
+ const app = express ( ) ;
10
+
11
+ // Parse POST data
12
+ app . use ( bodyParser . json ( ) ) ;
13
+
14
+ // Read the comments.json file
15
+ function readComments ( ) {
16
+ const comments = fs . readFileSync ( 'comments.json' , 'utf8' ) ;
17
+ return JSON . parse ( comments ) ;
18
+ }
19
+
20
+ // Write the comments.json file
21
+ function writeComments ( comments ) {
22
+ fs . writeFileSync ( 'comments.json' , JSON . stringify ( comments , null , 4 ) ) ;
23
+ }
24
+
25
+ // Get comments
26
+ app . get ( '/comments' , ( req , res ) => {
27
+ const comments = readComments ( ) ;
28
+ res . json ( comments ) ;
29
+ } ) ;
30
+
31
+ // Post comments
32
+ app . post ( '/comments' , ( req , res ) => {
33
+ const comments = readComments ( ) ;
34
+ comments . push ( req . body ) ;
35
+ writeComments ( comments ) ;
36
+ res . json ( comments ) ;
37
+ } ) ;
38
+
39
+ // Start server
40
+ app . listen ( 3000 , ( ) => {
41
+ console . log ( 'Server is listening at http://localhost:3000' ) ;
42
+ } ) ;
You can’t perform that action at this time.
0 commit comments