Как я могу gzip HTML с nodejs - PullRequest
       1

Как я могу gzip HTML с nodejs

0 голосов
/ 10 октября 2018

У меня есть сервер nodejs, и я хотел бы распечатать html.Я пытаюсь использовать [этот пост] [1] Дэвид предложил gzip html.Но я не вижу, чтобы html был gziped в chrome, и, кроме того, он вылетает Ошибка: ENOENT: нет такого файла или каталога, откройте './public/js/vendor/plyr.min.js.map'

Plyr отлично работал без ранее.

    var http = require('http');
    var fs = require('fs');
    var path = require('path');
    var url = require('url');
    var port = process.env.PORT || 1881; 

    http.createServer(function (request, response) {
        var filePath = '.' + request.url;
        if (filePath == './')
           filePath = './public/index.html';

        var extname = path.extname(filePath);
        var contentType = 'text/html';

var raw = fs.createReadStream(filePath);
    var acceptEncoding = request.headers['accept-encoding'];
    if (!acceptEncoding) {
        acceptEncoding = '';
    }

    // Note: this is not a conformant accept-encoding parser.
    // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
    if (acceptEncoding.match(/\bdeflate\b/)) {
        response.writeHead(200, { 'content-encoding': 'deflate' });
        raw.pipe(zlib.createDeflate()).pipe(response);
    } else if (acceptEncoding.match(/\bgzip\b/)) {
        response.writeHead(200, { 'content-encoding': 'gzip' });
        raw.pipe(zlib.createGzip()).pipe(response);
    } else {
        response.writeHead(200, {});
        raw.pipe(response);
    }

        fs.readFile(filePath, function(error, content) {
            if (error) {
                if(error.code == 'ENOENT'){
                    fs.readFile('./404.html', function(error, content) {
                        response.writeHead(200, { 'Content-Type': contentType });
                        response.end(content, 'utf-8');
                    });
                }
                else {
                    response.writeHead(500);
                    response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
                    response.end(); 
                }
            }
            else {
                response.writeHead(200, { 'Content-Type': contentType });
                response.end(content, 'utf-8');
            }
        });
    }).listen(port);
    console.log("Server Running on "+port+".\nLaunch http://localhost:"+port);


  [1]: /3986454/node-js-szhatie-gzip

1 Ответ

0 голосов
/ 11 октября 2018

Хорошо, вчера я снова был глупым :) Я должен был поместить компрессирующую часть в функцию fs.readFile.Это работает сейчас.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...