1- const http = require ( 'http' ) ;
2- const fs = require ( 'fs' ) ;
3- const path = require ( 'path' ) ;
4- const multiparty = require ( 'multiparty' ) ;
1+ const http = require ( 'http' ) ;
2+ const fs = require ( 'fs' ) ;
3+ const path = require ( 'path' ) ;
4+ const multiparty = require ( 'multiparty' ) ;
5+ const url = require ( 'url' ) ;
6+ const querystring = require ( 'querystring' ) ;
57
68const SERVER_PORT = 3000 ;
79
@@ -14,10 +16,22 @@ const CONTENT_TYPES = {
1416 '.pdf' : 'application/pdf'
1517} ;
1618
19+ function isBinaryResource ( contentType ) {
20+ if ( contentType === CONTENT_TYPES [ ".png" ] )
21+ return true ;
22+
23+ return false ;
24+ }
25+
26+ function stringifyContentIfNecessary ( content , contentType ) {
27+ if ( ! content )
28+ return content ;
29+
30+ return isBinaryResource ( contentType ) ? content : content . toString ( ) ;
31+ }
32+
1733http
1834 . createServer ( ( req , res ) => {
19- console . log ( req . url ) ;
20-
2135 if ( req . url === '/download-file' ) {
2236 const fileStream = fs . createReadStream ( './server/data/text-file.txt' ) ;
2337
4761 res . end ( resultHtml ) ;
4862 } ) ;
4963 }
64+
5065 else {
5166 const repositoryRoot = path . resolve ( __dirname , '..' ) ;
52- const resourcePath = path . join ( repositoryRoot , req . url ) ;
53- const content = fs . existsSync ( resourcePath ) ? fs . readFileSync ( resourcePath ) . toString ( ) : '' ;
67+ const parsedUrl = url . parse ( req . url ) ;
68+ const resourcePath = path . join ( repositoryRoot , parsedUrl . pathname ) ;
69+ let content = fs . existsSync ( resourcePath ) ? fs . readFileSync ( resourcePath ) : void 0 ;
5470 const contentType = CONTENT_TYPES [ path . extname ( resourcePath ) ] ;
71+ const delay = parseInt ( querystring . parse ( parsedUrl . query ) . delay || 0 ) ;
72+
73+ content = stringifyContentIfNecessary ( content , contentType ) ;
5574
5675 if ( contentType )
5776 res . setHeader ( 'content-type' , contentType ) ;
5877
59- res . end ( content ) ;
78+ setTimeout ( ( ) => {
79+ res . end ( content ) ;
80+ } , delay ) ;
6081 }
6182 } )
6283 . listen ( SERVER_PORT ) ;
0 commit comments