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

const http = require('http');
const fs = require('fs/promises');
const fsCb = require('fs');
const path = require('path');
const zlib = require('zlib');
const { pipeline } = require('stream');
const busboy = require('busboy');

const form = `<form action="http://localhost:5700/compress" method="POST" enctype="multipart/form-data" style="display: flex; flex-direction: column; max-width: 300px; row-gap: 12px">
<select name="compressionType">
<option value="gzip">gzip</option>
<option value="deflate">deflate</option>
<option value="br">br</option>
</select>
<input type="file" name="file" />
<input type="submit"/>
</form>`;

function createServer() {
/* Write your code here */
// Return instance of http.Server class
const acceptableCompression = {
gzip: { create: zlib.createGzip },
deflate: { create: zlib.createDeflate },
br: { create: zlib.createBrotliCompress },
};

const compressionExtensions = {
gzip: 'gz',
deflate: 'dfl',
br: 'br',
};

const acceptableEndpoint = {
index: {
path: 'index',
method: 'GET',
},
compress: {
path: 'compress',
method: 'POST',
},
};

const server = new http.Server();

server.on('request', async (req, res) => {
const normalizeUrl = new URL(req.url, `http://${req.headers.host}`);
const requestedPath = normalizeUrl.pathname.slice(1) || 'index';
const requestedMethod = req.method;

if (!Object.keys(acceptableEndpoint).includes(requestedPath)) {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');

return res.end('Non-existent endpoint');
}

if (
requestedPath === acceptableEndpoint.index.path &&
requestedMethod === acceptableEndpoint.index.method
) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');

return res.end(form);
}

if (
requestedPath === acceptableEndpoint.compress.path &&
requestedMethod === acceptableEndpoint.compress.method
) {
const field = {};
const file = {};
const writeStreamPromises = [];
const tmpDir = await fs.mkdtemp(path.resolve(__dirname, '..', 'upload-'));
const bb = busboy({ headers: req.headers });

res.on('close', () => {
fs.rm(tmpDir, { recursive: true });
});

bb.on('field', (name, value) => (field[name] = value));

bb.on('file', (name, fileStream, info) => {
const { filename, mimeType } = info;
const filePath = path.join(tmpDir, `${filename}`);

if (!filePath.startsWith(tmpDir)) {
res.writeHead(400, { 'content-type': 'text/plain' });

return res.end('Invalid filename');
}

file.fileName = filename;
file.mimeType = mimeType;
file.filePath = filePath;

const streamPromis = new Promise((resolve, reject) => {
const wrs = fsCb
.createWriteStream(filePath)
.on('finish', () => resolve())
.on('error', (er) => reject(er));

fileStream.on('error', (er) => reject(er));
fileStream.pipe(wrs);
});

writeStreamPromises.push(streamPromis);
});

bb.on('close', async () => {
if (!field.compressionType || !file.fileName) {
res.writeHead(400, { 'content-type': 'text/plain' });
res.end('form is invalid');
} else {
await Promise.all(writeStreamPromises);

const type = field.compressionType;

if (!acceptableCompression[type]) {
res.writeHead(400, { 'content-type': 'text/plain' });

return res.end('You entered the wrong format');
}

const readingFileStream = fsCb.createReadStream(file.filePath);
const compressionStream = acceptableCompression[type].create();
const resFileName = `${file.fileName}.${compressionExtensions[type]}`;

res.writeHead(200, {
'content-type': `application/${field.compressionType}`,
'content-disposition': `attachment; filename=${resFileName}`,
});

pipeline(readingFileStream, compressionStream, res, (err) => {
// eslint-disable-next-line no-console, curly
if (err) console.log(err);
});
}
});

req.pipe(bb);

return;
}

res.statusCode = 400;
res.setHeader('Content-Type', 'text/plain');
res.end('Not supported method');
});

server.on('error', () => {});

return server;
}

module.exports = {
Expand Down
Loading