Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution #142

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
145 changes: 143 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,149 @@
'use strict';

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

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
const filePath = path.join(__dirname, 'index.html');

fs.readFile(filePath, (err, data) => {
if (err) {
res.statusCode = 500;
res.end('Error loading HTML file');

return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
});

return;
}

if (req.method === 'GET' && req.url === '/compress') {
res.statusCode = 400;
res.end('GET method not allowed for /compress');

return;
}

if (req.method === 'POST' && req.url === '/compress') {
const boundary = req.headers['content-type'].split('boundary=')[1];

Choose a reason for hiding this comment

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

The code assumes that the 'Content-Type' header will always contain a boundary. It would be more robust to check if the 'Content-Type' header exists before attempting to split it.


if (!boundary) {
res.statusCode = 400;
res.end('Invalid Form');

return;
}

const chunks = [];

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

req.on('end', () => {
const buffer = Buffer.concat(chunks);
const parts = buffer.toString().split(`--${boundary}`);

Choose a reason for hiding this comment

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

Splitting the buffer by the boundary might not correctly handle the multipart form data if the boundary is not unique or if there are additional CRLF sequences. Consider using a library like 'multiparty' or 'busboy' to handle multipart form data parsing more reliably.


let fileName = '';
let fileBuffer;
let compressionType = '';

for (const part of parts) {
if (
part.includes(
'Content-Disposition: form-data; name="file"; filename="',
)
) {
const match = part.match(/filename="([^"]+)"/);

if (match) {
fileName = match[1];

const fileContentIndex = part.indexOf('\r\n\r\n') + 4;

fileBuffer = Buffer.from(
part.slice(fileContentIndex, -2),
'binary',
);
}
}

if (
part.includes(
'Content-Disposition: form-data; name="compressionType"',
)
) {
const match = part.match(/\r\n\r\n(\w+)\r\n/);

if (match) {
compressionType = match[1];
}
}
}

if (!fileName || !fileBuffer || !compressionType) {
res.statusCode = 400;
res.end('Invalid Form');

return;
}

const validCompressionTypes = ['gzip', 'deflate', 'br'];

if (!validCompressionTypes.includes(compressionType)) {
res.statusCode = 400;
res.end('Unsupported Compression Type');
Comment on lines +98 to +100

Choose a reason for hiding this comment

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

The error message 'Unsupported Compression Type' is returned for invalid compression types, but it might be helpful to include the supported types in the response to guide the user.


return;
}

const compressionMap = {
gzip: zlib.createGzip(),
deflate: zlib.createDeflate(),
br: zlib.createBrotliCompress(),
};

const compressedFileName = `${fileName}.${compressionType === 'gzip' ? 'gzip' : compressionType === 'deflate' ? 'deflate' : 'br'}`;

Choose a reason for hiding this comment

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

The logic for determining the file extension based on the compression type is correct, but it could be simplified by using a map similar to 'compressionMap' to avoid repetitive ternary operations.


const compressedStream = compressionMap[compressionType];
const compressedChunks = [];

compressedStream.on('data', (chunk) => compressedChunks.push(chunk));

compressedStream.on('end', () => {
const compressedBuffer = Buffer.concat(compressedChunks);

res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename=${compressedFileName}`,
});
res.end(compressedBuffer);
});

compressedStream.on('error', () => {
res.statusCode = 500;
res.end('Compression Error');
});

compressedStream.end(fileBuffer);
});

req.on('error', () => {
res.statusCode = 400;
res.end('Invalid Form');
});

return;
}

res.statusCode = 404;
res.end('Not Found');
});
}

module.exports = {
Expand Down
19 changes: 19 additions & 0 deletions src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/compress" method="post" enctype="multipart/form-data">
<input type="file" name="file" required/>
<select id="compressionType" name="compressionType" required>
<option value="gzip">gzip</option>
<option value="deflate">deflate</option>
<option value="br">br</option>
</select>
<button type="submit" >Submit</button>
</form>
</body>
</html>
Loading