File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ // Create web server
2+ const http = require ( 'http' ) ;
3+ const fs = require ( 'fs' ) ;
4+ const url = require ( 'url' ) ;
5+ const { parse } = require ( 'querystring' ) ;
6+
7+ const server = http . createServer ( ( req , res ) => {
8+ const path = url . parse ( req . url ) . pathname ;
9+ const params = url . parse ( req . url , true ) . query ;
10+ if ( path === '/add-comment' ) {
11+ let body = '' ;
12+ req . on ( 'data' , chunk => {
13+ body += chunk . toString ( ) ;
14+ } ) ;
15+ req . on ( 'end' , ( ) => {
16+ const comment = parse ( body ) . comment ;
17+ fs . appendFile ( 'comments.txt' , comment + '\n' , err => {
18+ if ( err ) {
19+ res . writeHead ( 500 ) ;
20+ res . end ( 'Error: ' + err ) ;
21+ return ;
22+ }
23+ res . writeHead ( 200 ) ;
24+ res . end ( 'Comment added' ) ;
25+ } ) ;
26+ } ) ;
27+ } else {
28+ res . writeHead ( 200 , { 'Content-Type' : 'text/html' } ) ;
29+ res . write ( '<form action="/add-comment" method="post">' ) ;
30+ res . write ( '<textarea name="comment"></textarea><br>' ) ;
31+ res . write ( '<input type="submit">' ) ;
32+ res . write ( '</form>' ) ;
33+ res . end ( ) ;
34+ }
35+ } ) ;
36+
37+ server . listen ( 3000 , ( ) => {
38+ console . log ( 'Server listening on port 3000' ) ;
39+ } ) ;
You can’t perform that action at this time.
0 commit comments