Skip to content

Commit e7532a7

Browse files
committed
2 parents 89b6589 + 20a2db1 commit e7532a7

39 files changed

+946
-3
lines changed

Lesson03/exercise_002/package.json

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,6 @@
33
"version": "1.0.0",
44
"description": "Second exercise for lesson 3",
55
"main": "index.js",
6-
"scripts": {
7-
"test": "echo \"Error: no test specified\" && exit 1"
8-
},
96
"repository": {
107
"type": "git",
118
"url": "git+https://github.com/TrainingByPackt/Professional-JavaScript.git",

Lesson03/exercise_003/index.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
const fs = require('fs');
2+
const http = require('http');
3+
const mime = require('mime');
4+
const path = require('path');
5+
const url = require('url');
6+
7+
function walkDirectory(dirPath, callback) {
8+
const dirents = fs.readdirSync(dirPath, { withFileTypes: true });
9+
10+
dirents.forEach(dirent => {
11+
if (dirent.isDirectory()) {
12+
walkDirectory(path.join(dirPath, dirent.name), callback);
13+
} else {
14+
callback(path.join(dirPath, dirent.name));
15+
}
16+
});
17+
}
18+
19+
const rootDirectory = path.resolve(process.argv[2] || './');
20+
21+
const files = new Set();
22+
walkDirectory(rootDirectory, (file) => {
23+
file = file.substr(rootDirectory.length);
24+
files.add(file);
25+
});
26+
console.log(`Found ${files.size} in '${rootDirectory}'...`);
27+
28+
const server = http.createServer();
29+
server.on('request', (request, response) => {
30+
const requestUrl = url.parse(request.url);
31+
const requestedPath = requestUrl.pathname;
32+
33+
if (!files.has(requestedPath)) {
34+
console.log('404 %s', requestUrl.href);
35+
response.writeHead(404);
36+
response.end();
37+
return;
38+
}
39+
40+
const contentType = mime.getType(path.extname(requestedPath));
41+
42+
console.log('200 %s', requestUrl.href);
43+
response.writeHead(200, { 'Content-type': contentType });
44+
fs.createReadStream(path.join(rootDirectory, requestedPath))
45+
.pipe(response);
46+
});
47+
48+
const port = 3000;
49+
console.log('Starting server on port %d.', port);
50+
console.log('Go to: http://localhost:%d', port);
51+
server.listen(port);

Lesson03/exercise_003/package-lock.json

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Lesson03/exercise_003/package.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "exercise_003",
3+
"version": "1.0.0",
4+
"description": "Static HTTP server.",
5+
"main": "index.js",
6+
"repository": {
7+
"type": "git",
8+
"url": "git+https://github.com/TrainingByPackt/Professional-JavaScript.git",
9+
"directory": "Lesson03/exercise_003"
10+
},
11+
"author": "",
12+
"license": "MIT",
13+
"dependencies": {
14+
"mime": "^2.4.4"
15+
}
16+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<html>
2+
<head>
3+
<link rel="stylesheet" type="text/css" href="css/semantic.min.css" />
4+
<link rel="stylesheet" type="text/css" href="css/store.css" />
5+
</head>
6+
<body>
7+
<section>
8+
<h1 class="title">Welcome to Fresh Products Store!</h1>
9+
<div class="ui items">
10+
{{#products}}
11+
<div class="item">
12+
<div class="image"><img src="{{image}}" /></div>
13+
<div class="content">
14+
<a class="header">{{name}}</a>
15+
<div class="meta">
16+
<span>{{currency price}} / {{unit}}</span>
17+
</div>
18+
<div class="description">{{description}}</div>
19+
<div class="extra">
20+
{{#tags}}
21+
<div class="ui label teal">{{this}}</div>
22+
{{/tags}}
23+
</div>
24+
</div>
25+
</div>
26+
{{/products}}
27+
</div>
28+
</section>
29+
</body>
30+
</html>

Lesson03/exercise_004/index.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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();

Lesson03/exercise_004/package-lock.json

Lines changed: 69 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Lesson03/exercise_004/package.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "exercise_004",
3+
"version": "1.0.0",
4+
"description": "Exercise that demonstrate how to create a dynamic web server",
5+
"main": "index.js",
6+
"repository": {
7+
"type": "git",
8+
"url": "git+https://github.com/TrainingByPackt/Professional-JavaScript.git"
9+
},
10+
"license": "MIT",
11+
"dependencies": {
12+
"handlebars": "^4.1.2",
13+
"mime": "^2.4.4"
14+
}
15+
}

0 commit comments

Comments
 (0)