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
42 changes: 40 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,46 @@
'use strict';

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

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}`);
let pathname = url.pathname;

if (req.url.includes('..')) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Invalid path');

return;
}

if (pathname.includes('//')) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');

return;
}

if (pathname === '/file' || pathname === '/file/') {
pathname = '/file/index.html';
}

if (pathname.startsWith('/file/')) {
fs.readFile(`.${pathname.replace('file', 'public')}`, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File Not Found');
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The Content-Type is hardcoded to text/plain. This will cause browsers to display HTML and CSS files as plain text instead of rendering them. Consider dynamically setting the Content-Type based on the requested file's extension (e.g., .html -> text/html).

res.end(data);
}
});
} else {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Please use /file/ prefix to load files');
}
});
}

module.exports = {
Expand Down
Loading