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

Add test solution #121

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
128 changes: 126 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,132 @@
/* eslint-disable no-useless-return */
/* eslint-disable no-console */
'use strict';

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

const uploadDir = path.join(__dirname, 'uploads');

if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}

function compressFile(filePath, compressionType, callback) {
const extension =
compressionType === 'gzip'
? '.gzip'

Choose a reason for hiding this comment

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

Avoid nesting ternaries

: compressionType === 'deflate'
? '.deflate'
: '.br';
const outputFilePath = `${filePath}${extension}`;
const compressStream =
compressionType === 'gzip'
? zlib.createGzip()

Choose a reason for hiding this comment

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

Avoid using nested ternaries

: compressionType === 'deflate'
? zlib.createDeflate()
: zlib.createBrotliCompress();

const input = fs.createReadStream(filePath);
const output = fs.createWriteStream(outputFilePath);

input
.pipe(compressStream)
.pipe(output)
.on('finish', () => callback(outputFilePath));
}

function parseMultipartData(body, boundary) {
const parts = body
.split(`--${boundary}`)
.filter((part) => part.trim() !== '' && part !== '--');
const parsed = {};

parts.forEach((part) => {
const headers = part.split('\r\n\r\n')[0];
const content = part.split('\r\n\r\n')[1]?.trimEnd();

if (headers.includes('filename')) {
const match = headers.match(/filename="(.+)"/);

if (match) {
parsed.fileName = match[1];
parsed.fileContent = content;
}
} else if (headers.includes('name="compressionType"')) {
parsed.compressionType = content;
}
});

return parsed;
}

function createServer() {
/* Write your code here */
// Return instance of http.Server class
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream(path.join(__dirname, '/index.html')).pipe(res);
} else if (req.method === 'GET' && req.url === '/compress') {
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end('Error requset');
} else if (req.method === 'POST' && req.url === '/compress') {
let body = '';

req.on('data', (chunk) => {
body += chunk.toString();
});

req.on('end', () => {
const boundary = req.headers['content-type']
.split('; ')[1]
.split('=')[1];

const { fileName, fileContent, compressionType } = parseMultipartData(
body,
boundary,
);

if (!fileName || !fileContent || !compressionType) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Invalid form data');

return;
}

const filePath = path.join(uploadDir, fileName);

fs.writeFileSync(filePath, fileContent, 'binary');

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

if (!validTypes.includes(compressionType)) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Unsupported compression type');

return;
}

compressFile(filePath, compressionType, (compressedFilePath) => {
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename=${path.basename(compressedFilePath)}`,
});

fs.createReadStream(compressedFilePath).pipe(res);
});
});

req.on('error', (err) => {
console.log('ERROR DANGER', err);
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});

return server;
}

module.exports = {
Expand Down
22 changes: 22 additions & 0 deletions src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width= , initial-scale=1.0">
<title>File Compression</title>
</head>
<body>
<h1>File Compression Form</h1>
<form action="/compress" method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file"><br/><br/>

<select name="compressionType" id="compressionType" required>
<option value="gzib">GZIP</option>
<option value="deflate">Deflate</option>
<option value="br">Brotli</option>
</select>

<button type="submit">Compress</button>
</form>
</body>
</html>
Loading