我尝试从以下位置连接代码: 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.stat或fs.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/