node.js - 我如何使用 nodejs 压缩 html
问题描述
我有一个 nodejs 服务器,我想 gzip html。我尝试使用 [this post][1] David 建议使用 gzip html。但我没有看到 html 在 chrome 中被 gzip,最重要的是,它崩溃了错误: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]: https://stackoverflow.com/questions/3894794/node-js-gzip-compression
解决方案
好的,所以我昨天又傻了 :) 我应该把压缩部分放在 fs.readFile 函数中。现在可以了。
推荐阅读
- ios - 如何在不使用情节提要的情况下在两个视图之间添加 UIButton?
- c# - Service Fabric 无状态服务能否通知其他实例?
- javascript - 如何让 setInterval() 在每次迭代之前等待一个间隔(比如 10 秒)?
- php - Laravel 更新 WhereHas 中的关系列
- php - 如何在我键入时通过 Jquery Ajax 将输入文本中的值传递给 php 函数?WordPress
- javascript - 如何使用 javascript 渲染 jinja 或 jinja2 模板
- java - 尝试将数据发送到网络服务器时,我的 android 应用程序崩溃
- angularjs - 如何在 Yii2 / Angular 中将 hashUrl 设置为模块的 defaultRoute
- c# - 如何使用 Microsoft.Office.Interop.Outlook 库使用 C# 读取 .eml 文件?
- python - readlines 产生一个空列表 Python