Skip to content
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
23 changes: 23 additions & 0 deletions .github/workflows/test.yml-template
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Test

on:
pull_request:
branches: [ master ]

jobs:
build:

runs-on: ubuntu-latest

strategy:
matrix:
node-version: [20.x]

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
31 changes: 27 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"devDependencies": {
"@faker-js/faker": "^8.4.1",
"@mate-academy/eslint-config": "latest",
"@mate-academy/scripts": "^1.8.6",
"@mate-academy/scripts": "^2.1.2",
"axios": "^1.7.2",
"eslint": "^8.57.0",
"eslint-plugin-jest": "^28.6.0",
Expand All @@ -30,5 +30,8 @@
},
"mateAcademy": {
"projectType": "javascript"
},
"dependencies": {
"busboy": "^1.6.0"
}
}
50 changes: 50 additions & 0 deletions public/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
body {
font-family: Arial, sans-serif;
background: #f5f5f5;
margin: 0;
padding: 0;

display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

.form {
background: #fff;
padding: 25px 30px;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
width: 320px;
display: flex;
flex-direction: column;
gap: 15px;
}

label {
font-weight: bold;
margin-bottom: 5px;
}

input[type="file"],
select {
padding: 8px;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 14px;
}

button {
padding: 10px;
background: #007bff;
border: none;
color: white;
font-size: 16px;
border-radius: 6px;
cursor: pointer;
transition: 0.2s;
}

button:hover {
background: #0056c7;
}
24 changes: 24 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<form action="/compress" method="POST" enctype="multipart/form-data" class="form">
<label>Select file:</label>
<input type="file" name="file" required />

<label>Compression type:</label>
<select name="compressionType" required>
<option value="gzip">GZIP</option>
<option value="deflate">Deflate</option>
<option value="br">Brotli</option>
</select>

<button type="submit">Compress</button>
</form>
</body>
</html>
161 changes: 159 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,165 @@
'use strict';

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

// EXTENSIONS EXPECTED BY TESTS
const EXT_MAP = {
gzip: 'gzip',
deflate: 'deflate',
br: 'br',
};
Comment on lines +10 to +14

Choose a reason for hiding this comment

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

EXT_MAP currently maps to the compression names (e.g. 'gzip') rather than the file extensions the tests require. Update the mapping so the stored extension values are exactly: gzip: 'gz', deflate: 'dfl', br: 'br' so the produced filename becomes file.txt.gz, file.txt.dfl, or file.txt.br as required.

Comment on lines +10 to +14

Choose a reason for hiding this comment

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

(HIGH) EXT_MAP currently maps to compression names ('gzip','deflate','br'). The tests expect file extensions so the produced filename must be e.g. file.txt.gz, file.txt.dfl, file.txt.br. Change the mapping to the extension tokens (for example gzip: 'gz', deflate: 'dfl', br: 'br') so outName becomes correct.


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 (req.method === 'POST' && url.pathname === '/compress') {
const bb = busboy({ headers: req.headers });

let compressionType = null;
let fileInfo = null;

bb.on('field', (name, val) => {
if (name === 'compressionType') {
compressionType = val;

if (fileInfo && !fileInfo.started) {
fileInfo.start();
}
}
});

bb.on('file', (name, file, info) => {
file.pause();

fileInfo = {
file,
info,
started: false,
start() {
if (this.started) {
return;
}
this.started = true;

if (!compressionType) {
return;
} // дочекаємося пізніше

if (!EXT_MAP[compressionType]) {
res.statusCode = 400;

return res.end('Invalid compressionType');
Comment on lines +55 to +58

Choose a reason for hiding this comment

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

(MEDIUM) When !EXT_MAP[compressionType] is detected you set res.statusCode = 400 and return res.end('Invalid compressionType'), but the incoming file stream was paused earlier (file.pause()) and is not resumed or destroyed. This can leave busboy/upload hanging. Resume or destroy the file stream (for example file.resume() or file.destroy()) before ending the response.

}

const outName = `${info.filename}.${EXT_MAP[compressionType]}`;

const compressor =
compressionType === 'gzip'
? zlib.createGzip()
: compressionType === 'deflate'
? zlib.createDeflate()
: zlib.createBrotliCompress();

res.statusCode = 200;

res.setHeader(
'Content-Disposition',
`attachment; filename=${outName}`,
Comment on lines +72 to +74

Choose a reason for hiding this comment

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

(LOW) Wrap the filename in quotes in the Content-Disposition header to handle spaces/special characters correctly. Use e.g. attachment; filename="${outName}" instead of attachment; filename=${outName}.

);

file.on('error', () => {
if (!res.headersSent) {
res.statusCode = 500;
}
res.end();
});

compressor.on('error', () => {
if (!res.headersSent) {
res.statusCode = 500;
}
res.end();
});

file.resume();
file.pipe(compressor).pipe(res);
},
};

if (compressionType) {
fileInfo.start();
}
});

bb.on('finish', () => {
if (!fileInfo) {
res.statusCode = 400;

return res.end('No file');
}

if (!compressionType) {
// прибираємо пайпи, якщо були
fileInfo.file.unpipe();

// дочитуємо файл до кінця, інакше busboy зависне
fileInfo.file.resume();
res.statusCode = 400;

return res.end('Missing compressionType');
}

if (!fileInfo.started) {
fileInfo.start();
}
});

req.pipe(bb);

return;
}

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

return;
}

const fileName = url.pathname.slice(1) || 'index.html';
const filePath = path.resolve('public', fileName);

if (!fs.existsSync(filePath)) {
res.statusCode = 404;

return res.end('file dont found');
}

const ext = path.extname(filePath);
const mimeTypes = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
};

res.setHeader('Content-Type', mimeTypes[ext] || 'text/plain');
fs.createReadStream(filePath).pipe(res);
});

return server;
}

module.exports = {
Expand Down
Loading