Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 61 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,67 @@
'use strict';

const http = require('http');
const path = require('path');
const fs = require('fs');

const MIME_TYPES = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.txt': 'text/plain',
};

function getMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase();

return MIME_TYPES[ext] || 'application/octet-stream';
}

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);

if (url.pathname === '/file') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Please specify a file path after /file/.');

return;
}
Comment on lines +29 to +34
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to the task description, a request to /file should return public/index.html. This block of code handles that case differently by returning a plain text message. The logic on line 25 is already set up to handle both /file and /file/ correctly, so this special check can be removed.

Comment on lines +29 to +34
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to the requirements, a request to /file should return public/index.html. This block prevents that by sending a text response instead. If you remove this if statement, the logic that follows will correctly handle this case by defaulting to index.html.


if (!url.pathname.startsWith('/file')) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Use /file/<path> to load files');

return;
}

const relativePath = url.pathname.replace(/^\/file\/?/, '') || 'index.html';
const publicDir = path.resolve(__dirname, '..', 'public');
const fullPath = path.resolve(publicDir, relativePath);

if (!fullPath.startsWith(publicDir + path.sep) && fullPath !== publicDir) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');

return;
}

try {
const data = fs.readFileSync(fullPath);
const contentType = getMimeType(fullPath);

res.writeHead(200, { 'Content-Type': contentType });
res.end(data);
} catch (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
}

module.exports = {
Expand Down
Loading