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

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

function createServer() {
/* Write your code here */
// Return instance of http.Server class
const server = new http.Server();

server.on('request', (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);

if (url.pathname === '/' && req.method === 'GET') {
fs.createReadStream(path.resolve('public', 'index.html')).pipe(res);

return;
}

if (url.pathname === '/add-expense' && req.method === 'POST') {
const chunks = [];

req.on('data', (chunk) => {
chunks.push(chunk);
});

req.on('end', () => {
const expensePath = path.resolve(__dirname, '..', 'db/expense.json');
const data = Buffer.concat(chunks).toString();

if (Object.keys(JSON.parse(data)).length !== 3) {
res.statusCode = 400;
res.setHeader('Content-type', 'text/plain');
res.end('All params must be completed');

return;
}

fs.writeFileSync(expensePath, data);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Issue: Using fs.writeFileSync inside an asynchronous request handler can block the event loop and degrade server performance, especially under concurrent requests. Consider using fs.writeFile (the asynchronous version) with a callback to avoid blocking the server.

res.statusCode = 200;
res.setHeader('Content-type', 'application/json');
res.end(data);
});
Comment on lines +62 to +66
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

You are using fs.writeFileSync with a callback, but the synchronous version does not accept a callback and will throw on error. This is a critical issue: switch to using fs.writeFile (the async version) with a callback to properly handle file write errors and only send the response after the write completes. This is necessary to ensure data integrity and proper error handling as required by the task.


return;
}

res.statusCode = 404;
res.end('Page not found');
});

return server;
}

module.exports = {
Expand Down