Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution #60

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
50 changes: 50 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1 +1,51 @@
'use strict';

const http = require('http');
const path = require('path');
const fs = require('fs');
const zlib = require('zlib');

function compression() {
const server = new http.Server();

server.on('request', (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const fileName = url.pathname.slice(1) || 'index.html';
const filePath = path.resolve('public', fileName);

if (!fs.existsSync(filePath)) {
res.statusCode = 404;
res.end('File not found');

return;
}

res.setHeader('Content-Encoding', 'gzip');

const fileStream = fs.createReadStrem(filePath);

const gzip = zlib.createGzip();

fileStream
.on('error', () => {})
.pipe(gzip)
.on('error', () => {})
.pipe(res)
.on('error', () => {});

Choose a reason for hiding this comment

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

here would be better to use pipeline


fileStream.on('error', (err) => {
res.statusCode = 500;
res.end(`Server error: ${err}`);
});

res.on('close', () => fileStream.destroy());
});

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

server.listen(3005);
}

module.exports = {
compression,
};
Loading