Skip to content
Open
Show file tree
Hide file tree
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
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
9 changes: 5 additions & 4 deletions package-lock.json

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

2 changes: 1 addition & 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.3",
"axios": "^1.7.2",
"eslint": "^8.57.0",
"eslint-plugin-jest": "^28.6.0",
Expand Down
37 changes: 37 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="/" />
<title>Document</title>
</head>
<body>
<h1>Compress your files!</h1>
<form
id="compressionForm"
action="/compress"
method="POST"
enctype="multipart/form-data"
>
<div class="form__item">
<label for="file">File:</label>
<input type="file" id="file" name="file" />
</div>

<div class="form__item">
<label for="compressionType">Compression Type:</label>
<select name="compressionType" id="compressionType">
<option value="" selected disabled>
Select type
</option>
<option value="gzip">GZIP</option>
<option value="deflate">Deflate</option>
<option value="brotli">Brotli</option>
<option value="der">der</option>
</select>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
114 changes: 112 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,118 @@
/* eslint-disable no-console */
'use strict';

const { Server } = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const { pipeline } = require('stream');
const zlib = require('zlib');
const formidable = require('formidable');

const compressMap = new Map([
['gzip', { compressor: () => zlib.createGzip() }],
['deflate', { compressor: () => zlib.createDeflate() }],
['br', { compressor: () => zlib.createBrotliCompress() }],
]);

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

server.on('request', (req, res) => {
try {
const url = new URL(req.url || '', `http://${req.headers.host}`);
const requestedPath = url.pathname.slice(1) || 'index.html';
const realPath = path.join('public', requestedPath);
const mimeType = mime.contentType(path.extname(realPath)) || 'text/plain';
const form = new formidable.IncomingForm();

if (requestedPath === 'compress') {
if (req.method === 'POST') {
form.parse(req, (err, fields, files) => {
if (err) {
console.log('[Error]: ', err);
res.statusCode = 400;
res.end('Error: form is invalid');

return;
}

const file = Array.isArray(files.file) ? files.file[0] : files.file;
const compressionType = Array.isArray(fields.compressionType)
? fields.compressionType[0]
: fields.compressionType;

if (
!file ||
!compressionType ||
!compressMap.has(compressionType)
) {
res.statusCode = 400;
res.end('Error: File or compressionType is missing');

return;
}

const inputPath = file.filepath;
const readStream = fs.createReadStream(inputPath);
const { compressor } = compressMap.get(compressionType);

res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename=${file.originalFilename}.${compressionType}`,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The requirement specifies the compressed file extensions should be .gz for gzip and .dfl for deflate. Currently, you are using the compressionType directly, which results in .gzip and .deflate. You might want to store the correct extension in your compressMap and use it here.

});

pipeline(readStream, compressor(), res, (error) => {
fs.unlink(file.filepath, () => {});

if (error) {
console.log(error);

if (!res.headersSent) {
res.statusCode = 500;
res.end('Error: Compression failed!');
} else {
res.destroy();
}
}
});

req.on('close', () => {
readStream.destroy();
compressor.destroy();
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 line will cause a runtime error. The compressor variable here refers to the function from compressMap (e.g., () => zlib.createGzip()), not the actual stream instance. A function doesn't have a .destroy() method. You need to save the stream instance created by compressor() inside the pipeline to a variable and then call .destroy() on that variable here.

});
});
} else {
res.statusCode = 400;
res.end('Error: Wrong method!');
}

return;
}

if (!fs.existsSync(realPath)) {
res.statusCode = 404;
res.end('Not Found');

return;
}

const html = fs.readFileSync(realPath);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The task requires using streams for I/O operations. fs.readFileSync reads the entire file into memory before sending it, which is not a stream-based approach. Consider using fs.createReadStream() and piping it to the response stream (res) to fulfill this requirement.


res.statusCode = 200;
res.setHeader('Content-Type', mimeType);
res.end(html);
} catch (error) {
res.statusCode = 500;
res.end('Server Error');
}
});

server.on('error', (error) => {
console.error('An error occurred:', error);
});

return server;
}

module.exports = {
Expand Down
Loading