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..e267868 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,10 +9,13 @@ "version": "1.0.0", "hasInstallScript": true, "license": "GPL-3.0", + "dependencies": { + "busboy": "^1.6.0" + }, "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", @@ -1487,10 +1490,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.2", + "resolved": "https://registry.npmjs.org/@mate-academy/scripts/-/scripts-2.1.2.tgz", + "integrity": "sha512-gUXFdqqOfYzF9R3RSx2pCa5GLdOkxB9bFbF+dpUpzucdgGAANqOGdqpmNnMj+e3xA9YHraUWq3xo9cwe5vD9pQ==", "dev": true, + "license": "MIT", "dependencies": { "@octokit/rest": "^17.11.2", "@types/get-port": "^4.2.0", @@ -2739,6 +2743,17 @@ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, "node_modules/call-bind": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", @@ -8040,6 +8055,14 @@ "node": ">=8" } }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/string-length": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", diff --git a/package.json b/package.json index 1d03d64..bf27fc7 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.2", "axios": "^1.7.2", "eslint": "^8.57.0", "eslint-plugin-jest": "^28.6.0", @@ -30,5 +30,8 @@ }, "mateAcademy": { "projectType": "javascript" + }, + "dependencies": { + "busboy": "^1.6.0" } } diff --git a/readme.md b/readme.md index e3ae78f..6bb555d 100644 --- a/readme.md +++ b/readme.md @@ -8,6 +8,7 @@ Implement a page with HTML `form` that allows to: - original file: `file.txt` - compression type: `gzip` - compressed file: `file.txt.gz` + To pass the task you also need to implement a server that: - use Streams diff --git a/src/createServer.js b/src/createServer.js index 1cf1dda..15cba1b 100644 --- a/src/createServer.js +++ b/src/createServer.js @@ -1,10 +1,160 @@ 'use strict'; +const http = require('http'); +const path = require('path'); +const zlib = require('node:zlib'); +const { Readable } = require('stream'); + +const extMap = { gzip: 'gzip', deflate: 'deflate', br: 'br' }; + function createServer() { - /* Write your code here */ - // Return instance of http.Server class + return http.createServer(async (req, res) => { + if (req.url === '/' && req.method === 'GET') { + res.statusCode = 200; + res.end('OK'); + + return; + } + + if (req.url !== '/compress') { + res.statusCode = 404; + res.end('Not Found'); + + return; + } + + if (req.method !== 'POST') { + res.statusCode = 400; + res.end('Incorrect form method'); + + return; + } + + const ct = req.headers['content-type']; + + if (!ct || !ct.includes('multipart/form-data')) { + res.statusCode = 400; + res.end('Expected multipart/form-data'); + + return; + } + + const boundary = ct.split('boundary=')[1]?.replace(/(^"|"$)/g, ''); + + if (!boundary) { + res.statusCode = 400; + res.end('Missing boundary'); + + return; + } + + const chunks = []; + + for await (const chunk of req) { + chunks.push(chunk); + } + + const body = Buffer.concat(chunks); + + const boundaryBuf = Buffer.from(`--${boundary}`); + let start = 0; + const parts = []; + + while (true) { + const idx = body.indexOf(boundaryBuf, start); + + if (idx === -1) { + break; + } + + const nextIdx = body.indexOf(boundaryBuf, idx + boundaryBuf.length); + const end = nextIdx !== -1 ? nextIdx : body.length; + + parts.push(body.slice(idx + boundaryBuf.length, end)); + start = end; + } + + let fileBuffer = null; + let filename = null; + let type = null; + + for (const part of parts) { + let p = part; + + if (p.slice(0, 2).toString() === '\r\n') { + p = p.slice(2); + } + + const delimiter = Buffer.from('\r\n\r\n'); + const idx = p.indexOf(delimiter); + + if (idx === -1) { + continue; + } + + const headersBuf = p.slice(0, idx); + const bodyBuf = p.slice(idx + delimiter.length); + const headersStr = headersBuf.toString('utf8').trim(); + + if (headersStr.includes('name="compressionType"')) { + type = bodyBuf.toString('utf8').trim().toLowerCase(); + + if (!['gzip', 'deflate', 'br'].includes(type)) { + res.statusCode = 400; + res.end('Unsupported compression type'); + + return; + } + } + + if (headersStr.includes('name="file"')) { + const match = headersStr.match(/filename="(.+?)"/); + + filename = match ? match[1] : 'file'; + + let endIdx = bodyBuf.length; + + if (bodyBuf.slice(-2).toString() === '\r\n') { + endIdx -= 2; + } + fileBuffer = bodyBuf.slice(0, endIdx); + } + } + + if (!fileBuffer || !type) { + res.statusCode = 400; + res.end('Missing file or compressionType'); + + return; + } + + const compressor = + type === 'gzip' + ? zlib.createGzip() + : type === 'deflate' + ? zlib.createDeflate() + : zlib.createBrotliCompress(); + + const compressedFileName = `${path.basename(filename)}.${extMap[type]}`; + + res.statusCode = 200; + res.setHeader('Content-Type', 'application/octet-stream'); + + res.setHeader( + 'Content-Disposition', + `attachment; filename=${compressedFileName}`, + ); + + const stream = Readable.from([fileBuffer]); + + stream + .pipe(compressor) + .pipe(res) + .on('error', () => { + res.statusCode = 500; + res.end('Compression error'); + }); + }); } -module.exports = { - createServer, -}; +module.exports = { createServer }; diff --git a/src/index.html b/src/index.html new file mode 100644 index 0000000..69dfb76 --- /dev/null +++ b/src/index.html @@ -0,0 +1,34 @@ + + + + + + Document + + +
+

File Compression

+ +
+ + + +
+
+ + + + +
+
+ + +
+
+ + + \ No newline at end of file