简体   繁体   中英

I deployed my node app on Heroku and want to enable Gzip compression, any tips?

I tried to wire up a code from: https://github.com/wimagguc/nodejs-static-http-with-gzip/blob/master/http-with-gzip.js Directories and Server.js File I made changes by adding the code:

path.exists(filePath, function(exists) {

    if (exists) {
        fs.readFile(filePath, function(error, content) {
            if (error) {
                response.writeHead(500);
                response.end();
            }
            else {
                var raw = fs.createReadStream(filePath);

                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);
                }
            }
        });
    }
    else {
        response.writeHead(404);
        response.end();
    }

in the server.js at:

app.get('/', (req, res) => {
//this place
    res.render('home.hbs', {
    pageTitle: 'Home Page',
    welcomeMess: 'Welcome to my Site'
})

}); the error: path.exists is not a function. but i could not understand the same and broke my app.

i was hoping to get a file that is gzipped. I am using express for handling the server

The problem is the code you use relies on old node versions. path.exists was replaced with fs.exists . You code could be like this (with minimal changes)

var fs = require("fs");
//...
path.exists(filePath, function(exists) {
    //...
}

Be aware that this method is deprecated and you should look for alternatives either use fs.stat or fs.access or even path-exists package if you don't mind external dependency. Anyway with fs.access it would be like this

fs.access(filePath, (err) => {
  if (err) {
    response.writeHead(404);
    response.end();
  }else{
    // ... rest of the method (here you know file exists and accessible)
  }      
});

The difference being the error is the first prameter in the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM