From cad2c5e85e5cd24785e8de10d2504a209ace280d Mon Sep 17 00:00:00 2001 From: diamat1997 Date: Tue, 14 Nov 2023 15:39:42 +0200 Subject: [PATCH] add task solution --- src/index.js | 114 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) diff --git a/src/index.js b/src/index.js index ad9a93a..6e7cd19 100644 --- a/src/index.js +++ b/src/index.js @@ -1 +1,115 @@ +/* eslint-disable no-console */ 'use strict'; + +const http = require('http'); +const fs = require('fs'); +const zlib = require('zlib'); +const formidable = require('formidable'); +const { pipeline } = require('stream'); + +const PORT = process.env.PORT || '3000'; + +const server = http.Server(); + +server.on('request', (req, res) => { + if (req.url === '/download' && req.method === 'POST') { + const form = new formidable.IncomingForm(); + + form.parse(req, (err, fields, files) => { + if (err) { + res.statusCode = 400; + res.end(JSON.stringify(err)); + + return; + } + + const { file } = files; + const { compression } = fields; + + if (!file || !compression) { + res.statusCode = 400; + res.end('Please select a file and compression type'); + + return; + } + + const readStream = fs.createReadStream(file.filepath); + + let compressionStream; + let extension; + + switch (compression) { + case 'gzip': + extension = '.gzip'; + compressionStream = zlib.createGzip(); + break; + case 'deflate': + extension = '.dfl'; + compressionStream = zlib.createDeflate(); + break; + case 'br': + extension = '.br'; + compressionStream = zlib.createBrotliCompress(); + break; + } + + res.setHeader('Content-Encoding', extension); + + const fileName = file.originalFilename + extension; + + pipeline(readStream, compressionStream, res, (error) => { + if (error) { + console.log(error); + + res.end(JSON.stringify(err)); + } + }); + + res.setHeader('Content-Type', 'application/octet-stream'); + + res.setHeader( + 'Content-Disposition', + `attachment; filename=${fileName}` + ); + + res.statusCode = 200; + res.end(); + }); + } else if (req.url === '/' && req.method === 'GET') { + res.writeHead(200, { 'Content-Type': 'text/html' }); + + res.end(` + + + + + + Document + + +
+ + + +
+ + + `); + } +}); + +server.on('error', () => {}); + +server.listen(PORT, () => { + console.log(`Server running at http://localhost:${PORT}`); +});