From f9c7bba4e487d9b886b47bebfea53663350516de Mon Sep 17 00:00:00 2001 From: Yaroslav Date: Thu, 2 Apr 2026 18:02:38 +0300 Subject: [PATCH 1/4] added solution --- .github/workflows/test.yml-template | 23 +++ package-lock.json | 9 +- package.json | 2 +- src/createServer.js | 233 +++++++++++++++++++++++++++- src/index.html | 23 +++ 5 files changed, 283 insertions(+), 7 deletions(-) create mode 100644 .github/workflows/test.yml-template create mode 100644 src/index.html diff --git a/.github/workflows/test.yml-template b/.github/workflows/test.yml-template new file mode 100644 index 0000000..bb13dfc --- /dev/null +++ b/.github/workflows/test.yml-template @@ -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 diff --git a/package-lock.json b/package-lock.json index d0b3b95..3650660 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,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", @@ -1487,10 +1487,11 @@ } }, "node_modules/@mate-academy/scripts": { - "version": "1.8.6", - "resolved": "https://registry.npmjs.org/@mate-academy/scripts/-/scripts-1.8.6.tgz", - "integrity": "sha512-b4om/whj4G9emyi84ORE3FRZzCRwRIesr8tJHXa8EvJdOaAPDpzcJ8A0sFfMsWH9NUOVmOwkBtOXDu5eZZ00Ig==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@mate-academy/scripts/-/scripts-2.1.3.tgz", + "integrity": "sha512-a07wHTj/1QUK2Aac5zHad+sGw4rIvcNl5lJmJpAD7OxeSbnCdyI6RXUHwXhjF5MaVo9YHrJ0xVahyERS2IIyBQ==", "dev": true, + "license": "MIT", "dependencies": { "@octokit/rest": "^17.11.2", "@types/get-port": "^4.2.0", diff --git a/package.json b/package.json index 1d03d64..8e6392d 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/createServer.js b/src/createServer.js index 1cf1dda..8f16f0b 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -1,8 +1,237 @@ 'use strict'; +const http = require('http'); +const { Readable } = require('stream'); +const zlib = require('zlib'); + +const compressors = { + gzip: zlib.createGzip, + deflate: zlib.createDeflate, + br: zlib.createBrotliCompress, +}; + +const extensions = { + gzip: '.gzip', + deflate: '.deflate', + br: '.br', +}; + +async function readRequestBody(req) { + const chunks = []; + + for await (const chunk of req) { + chunks.push(chunk); + } + + return Buffer.concat(chunks); +} + +function getBoundary(contentType = '') { + const match = contentType.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + + return match ? match[1] || match[2] : null; +} + +function parsePartHeaders(headerText) { + const headers = {}; + + headerText.split('\r\n').forEach((line) => { + const idx = line.indexOf(':'); + + if (idx === -1) { + return; + } + + const key = line.slice(0, idx).trim().toLowerCase(); + const value = line.slice(idx + 1).trim(); + + headers[key] = value; + }); + + return headers; +} + +function parseContentDisposition(value = '') { + const nameMatch = value.match(/name="([^"]+)"/i); + const filenameMatch = value.match(/filename="([^"]*)"/i); + + return { + name: nameMatch ? nameMatch[1] : null, + filename: filenameMatch ? filenameMatch[1] : null, + }; +} + +function trimCrlf(buf) { + if (buf.length >= 2 && buf.slice(-2).toString() === '\r\n') { + return buf.slice(0, -2); + } + + return buf; +} + +function parseMultipart(bodyBuffer, boundary) { + const boundaryToken = Buffer.from(`--${boundary}`); + const result = { + fields: {}, + file: null, + }; + + let pos = 0; + const first = bodyBuffer.indexOf(boundaryToken, pos); + + if (first !== 0) { + return null; + } + + pos = first; + + while (pos < bodyBuffer.length) { + const boundaryStart = bodyBuffer.indexOf(boundaryToken, pos); + + if (boundaryStart === -1) { + break; + } + + let partStart = boundaryStart + boundaryToken.length; + + // eslint-disable-next-line + const isFinal = + bodyBuffer.slice(partStart, partStart + 2).toString() === '--'; + + if (isFinal) { + break; + } + + if (bodyBuffer.slice(partStart, partStart + 2).toString() === '\r\n') { + partStart += 2; + } + + const headersEnd = bodyBuffer.indexOf(Buffer.from('\r\n\r\n'), partStart); + + if (headersEnd === -1) { + return null; + } + + const headerText = bodyBuffer.slice(partStart, headersEnd).toString('utf8'); + const headers = parsePartHeaders(headerText); + + const cd = parseContentDisposition(headers['content-disposition']); + + if (!cd.name) { + return null; + } + + const contentStart = headersEnd + 4; + + const nextBoundary = bodyBuffer.indexOf(boundaryToken, contentStart); + + if (nextBoundary === -1) { + return null; + } + + const rawContent = bodyBuffer.slice(contentStart, nextBoundary); + const content = trimCrlf(rawContent); + + if (cd.filename !== null) { + result.file = { + fieldName: cd.name, + filename: cd.filename, + buffer: content, + }; + } else { + result.fields[cd.name] = content.toString('utf8').trim(); + } + + pos = nextBoundary; + } + + return result; +} + function createServer() { - /* Write your code here */ - // Return instance of http.Server class + return http.createServer(async (req, res) => { + if (req.method === 'GET' && req.url === '/') { + res.statusCode = 200; + res.end(); + + return; + } + + if (req.url !== '/compress') { + res.statusCode = 404; + res.end(); + + return; + } + + if (req.method !== 'POST') { + res.statusCode = 400; + res.end(); + + return; + } + + const contentType = req.headers['content-type'] || ''; + const boundary = getBoundary(contentType); + + if (!boundary) { + res.statusCode = 400; + res.end(); + + return; + } + + let body; + + try { + body = await readRequestBody(req); + } catch (error) { + res.statusCode = 400; + res.end(); + + return; + } + + const parsed = parseMultipart(body, boundary); + + if (!parsed) { + res.statusCode = 400; + res.end(); + + return; + } + + const compressionType = parsed.fields.compressionType; + const file = parsed.file; + + if ( + !compressionType || + !file || + file.fieldName !== 'file' || + !file.filename + ) { + res.statusCode = 400; + res.end(); + + return; + } + + if (!compressors[compressionType]) { + res.statusCode = 400; + res.end(); + + return; + } + + const compressor = compressors[compressionType](); + const outName = `${file.filename}${extensions[compressionType]}`; + + res.writeHead(200, { + 'Content-Disposition': `attachment; filename=${outName}`, + }); + + Readable.from(file.buffer).pipe(compressor).pipe(res); + }); } module.exports = { diff --git a/src/index.html b/src/index.html new file mode 100644 index 0000000..e61df18 --- /dev/null +++ b/src/index.html @@ -0,0 +1,23 @@ + + + + + + Document + + +
+
+
+ +
+ + +
+ + + From 39d83400d87c92b24326cb485b62270e67e27cdb Mon Sep 17 00:00:00 2001 From: Yaroslav Date: Thu, 2 Apr 2026 18:45:23 +0300 Subject: [PATCH 2/4] rename gzip -> .gz deflate -> .dfl --- src/createServer.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/createServer.js b/src/createServer.js index 8f16f0b..b6747ef 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -11,8 +11,8 @@ const compressors = { }; const extensions = { - gzip: '.gzip', - deflate: '.deflate', + gzip: '.gz', + deflate: '.dfl', br: '.br', }; From 27684134dc29a4f3bef041357b6577ea4f60deda Mon Sep 17 00:00:00 2001 From: Yaroslav Date: Thu, 2 Apr 2026 19:03:05 +0300 Subject: [PATCH 3/4] returned to stable version --- src/createServer.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/createServer.js b/src/createServer.js index b6747ef..8f16f0b 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -11,8 +11,8 @@ const compressors = { }; const extensions = { - gzip: '.gz', - deflate: '.dfl', + gzip: '.gzip', + deflate: '.deflate', br: '.br', }; From d603ff336a6e8f41fabb65f5a876f17808d1e487 Mon Sep 17 00:00:00 2001 From: Yaroslav Date: Fri, 3 Apr 2026 09:08:35 +0300 Subject: [PATCH 4/4] fix --- src/createServer.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/createServer.js b/src/createServer.js index 8f16f0b..ed181d9 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -16,6 +16,12 @@ const extensions = { br: '.br', }; +function getBoundary(contentType = '') { + const match = contentType.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + + return match ? match[1] || match[2] : null; +} + async function readRequestBody(req) { const chunks = []; @@ -26,12 +32,6 @@ async function readRequestBody(req) { return Buffer.concat(chunks); } -function getBoundary(contentType = '') { - const match = contentType.match(/boundary=(?:"([^"]+)"|([^;]+))/i); - - return match ? match[1] || match[2] : null; -} - function parsePartHeaders(headerText) { const headers = {};