|
| 1 | +const fs = require('fs'); |
| 2 | +const handlebars = require('handlebars'); |
| 3 | +const http = require('http'); |
| 4 | +const mime = require('mime'); |
| 5 | +const path = require('path'); |
| 6 | +const url = require('url'); |
| 7 | + |
| 8 | +const staticDir = path.resolve(`${__dirname}/static`); |
| 9 | +console.log(`Static resources from ${staticDir}`); |
| 10 | + |
| 11 | +const data = fs.readFileSync('products.json'); |
| 12 | +const products = JSON.parse(data.toString()); |
| 13 | +console.log(`Loaded ${products.length} products...`); |
| 14 | + |
| 15 | +handlebars.registerHelper('currency', (number) => `$${number.toFixed(2)}`); |
| 16 | + |
| 17 | +const htmlString = fs.readFileSync('html/index.html').toString(); |
| 18 | +const template = handlebars.compile(htmlString); |
| 19 | +function handleProductsPage(requestUrl, response) { |
| 20 | + response.writeHead(200); |
| 21 | + response.write(template({ products: products })); |
| 22 | + response.end(); |
| 23 | +} |
| 24 | + |
| 25 | +function handleStaticFile(pathname, response) { |
| 26 | + // For security reasons, only serve files from static directory |
| 27 | + const fullPath = path.join(staticDir, pathname); |
| 28 | + |
| 29 | + // Check if file exists and is readable |
| 30 | + fs.access(fullPath, fs.constants.R_OK, (error) => { |
| 31 | + if (error) { |
| 32 | + console.error(`File is not readable: ${fullPath}`, error); |
| 33 | + response.writeHead(404); |
| 34 | + response.end(); |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + const contentType = mime.getType(path.extname(fullPath)); |
| 39 | + response.writeHead(200, { 'Content-type': contentType }); |
| 40 | + fs.createReadStream(fullPath) |
| 41 | + .pipe(response); |
| 42 | + }); |
| 43 | +} |
| 44 | + |
| 45 | +function handleRequest(request, response) { |
| 46 | + const requestUrl = url.parse(request.url); |
| 47 | + const pathname = requestUrl.pathname; |
| 48 | + |
| 49 | + if (pathname == '/' || pathname == '/index.html') { |
| 50 | + handleProductsPage(requestUrl, response); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + handleStaticFile(pathname, response); |
| 55 | +} |
| 56 | + |
| 57 | +function initializeServer() { |
| 58 | + const server = http.createServer(); |
| 59 | + server.on('request', handleRequest); |
| 60 | + |
| 61 | + const port = 3000; |
| 62 | + console.log('Go to: http://localhost:%d', port); |
| 63 | + server.listen(port); |
| 64 | +} |
| 65 | + |
| 66 | +initializeServer(); |
0 commit comments