Skip to content

Commit d579c47

Browse files
committed
Add exercise 3 for lesson 3
1 parent 2436c27 commit d579c47

3 files changed

Lines changed: 83 additions & 0 deletions

File tree

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: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"name": "exercise_003",
3+
"version": "1.0.0",
4+
"description": "Static HTTP server.",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"repository": {
10+
"type": "git",
11+
"url": "git+https://github.com/TrainingByPackt/Professional-JavaScript.git",
12+
"directory": "Lesson03/exercise_003"
13+
},
14+
"author": "",
15+
"license": "MIT",
16+
"dependencies": {
17+
"mime": "^2.4.4"
18+
}
19+
}

0 commit comments

Comments
 (0)