我如何用nodejs gzip html

时间:2018-10-10 14:15:43

标签: node.js gzip

我有一个nodejs服务器,我想用gzip压缩html。 我尝试使用[this post] [1]让David建议使用gzip html。 但是我没有看到html用chrome压缩过的html,而且它崩溃了错误:ENOENT:没有这样的文件或目录,打开'./public/js/vendor/plyr.min.js.map'< / p>

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]: https://stackoverflow.com/questions/3894794/node-js-gzip-compression

1 个答案:

答案 0 :(得分:0)

好,所以昨天我又很愚蠢:) 我应该把压缩部分放在fs.readFile函数中。 现在可以使用了。