Skip to content
Open
Changes from 1 commit
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: 63 additions & 0 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,71 @@
'use strict';

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

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

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

return;
}

if (!url.startsWith('/file/')) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This condition incorrectly blocks requests to /file. According to the requirements, /file should be treated the same as /file/ and serve index.html. This check should be adjusted to allow the /file path to be handled by the file-serving logic below.

res.statusCode = 200;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

A 200 OK status code is not appropriate here, as you're handling a request for an invalid path. This should be a client error status code, like 400 Bad Request, to be consistent with your other error handling (e.g., on line 14).

res.setHeader('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.

When serving index.html, the Content-Type header should be text/html. Setting it to text/plain will cause browsers to display the HTML source code as plain text instead of rendering it as a webpage.


return res.end('Use /file/<filename> to load files');
}

const publicDir = path.resolve(__dirname, '..', 'public');
let filePath = url.slice(6);

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

if (filePath.includes('..')) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Bad Request');

return;
}

if (filePath.includes('//')) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Bad Request');

return;
}

const fullPath = path.join(publicDir, filePath);

if (!fullPath.startsWith(publicDir)) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Bad Request');

return;
}

fs.readFile(fullPath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File not found');

return;
}

res.writeHead(200);
res.end(data);
});
});
}

module.exports = {
Expand Down