node.js - 我在 Heroku 上部署了我的 Node 应用程序,并且想要启用 Gzip 压缩,有什么建议吗?

标签 node.js gzip

我尝试从以下位置连接代码: https://github.com/wimagguc/nodejs-static-http-with-gzip/blob/master/http-with-gzip.js Directories and Server.js File 我通过添加代码进行了更改:

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();
    }

在 server.js 中:

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

}); 错误:path.exists 不是函数。 但我无法理解并破坏了我的应用程序。

我希望获得一个 gzip 压缩的文件。 我正在使用express来处理服务器

最佳答案

问题是您使用的代码依赖于旧的 Node 版本。 path.exists 已替换为 fs.exists。您的代码可能是这样的(只需很少的更改)

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

请注意,此方法已被弃用,您应该寻找替代方法,或者使用 fs.statfs.access甚至path-exists如果您不介意外部依赖,请打包。无论如何,使用 fs.access 就会像这样

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

区别在于错误是回调中的第一个参数。

关于node.js - 我在 Heroku 上部署了我的 Node 应用程序,并且想要启用 Gzip 压缩,有什么建议吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49717108/

相关文章:

javascript - JavaScript 中带偏移量的 GZip 解压

javascript - 将base64音频转换为文件

c# - MVC 4 - JSON ajax 操作结果的 GZIP 压缩

node.js - Mongoose @set 和 $unset 条件

node.js - 在node.js中捕获请求url

c++ - C++ 中的 ZLib 解压缩

scala - 使用 Gzip Play Framework 不起作用

c# - Gzipped 内容不反射(reflect)输入

node.js - Gitlab CI 变量返回空字符串?

node.js - 使用 Sinon 时,如何替换 stub 实例中的 stub 函数?