@@ -5,40 +5,35 @@ const mime = require('mime');
55const path = require ( 'path' ) ;
66const url = require ( 'url' ) ;
77
8- const staticDir = path . resolve ( '. /static' ) ;
8+ const staticDir = path . resolve ( ` ${ __dirname } /static` ) ;
99console . log ( `Static resources from ${ staticDir } ` ) ;
1010
1111const data = fs . readFileSync ( 'products.json' ) ;
1212const products = JSON . parse ( data . toString ( ) ) ;
1313console . log ( `Loaded ${ products . length } products...` ) ;
1414
15- handlebars . registerHelper ( 'currency' , ( number ) => number . toFixed ( 2 ) ) ;
16-
17- function handleNotFound ( response ) {
18- response . writeHead ( 404 ) ;
19- response . end ( ) ;
20- }
15+ handlebars . registerHelper ( 'currency' , ( number ) => `$${ number . toFixed ( 2 ) } ` ) ;
2116
17+ const htmlTemplate = fs . readFileSync ( 'html/index.html' ) . toString ( ) ;
2218function handleProductsPage ( requestUrl , response ) {
23- const template = handlebars . compile ( fs . readFileSync ( 'html/index.html' ) . toString ( ) ) ;
19+ const template = handlebars . compile ( htmlTemplate ) ;
2420
2521 response . writeHead ( 200 ) ;
26- response . write ( template ( { products } ) ) ;
22+ response . write ( template ( { products : products } ) ) ;
2723 response . end ( ) ;
2824}
2925
3026function handleStaticFile ( pathname , response ) {
3127 // For security reasons, only serve files from static directory
32- const fullPath = path . resolve ( `static${ pathname } ` ) ;
33- if ( ! fullPath . startsWith ( staticDir ) ) {
34- return handleNotFound ( response ) ;
35- }
28+ const fullPath = path . join ( staticDir , pathname ) ;
3629
3730 // Check if file exists and is readable
3831 fs . access ( fullPath , fs . constants . R_OK , ( error ) => {
3932 if ( error ) {
4033 console . error ( `File is not readable: ${ fullPath } ` , error ) ;
41- return handleNotFound ( response ) ;
34+ response . writeHead ( 404 ) ;
35+ response . end ( ) ;
36+ return ;
4237 }
4338
4439 const contentType = mime . getType ( path . extname ( fullPath ) ) ;
0 commit comments