作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我目前正在使用代理服务器,在这种情况下,我们必须修改通过它推送的数据(通过使用正则表达式)。
在大多数情况下它工作正常,除了使用 gzip 作为内容编码的网站(我认为),我遇到了一个名为 compress 的模块。并尝试通过解压缩/gunzip 流推送我收到的 block ,但结果并不像我预期的那样。 (代码见下方)
想我会发布一些代码来支持我的概率,这是加载了 mvc (express) 的代理:
module.exports = {
index: function(request, response){
var iframe_url = "www.nu.nl"; // site with gzip encoding
var http = require('http');
var httpClient = http.createClient(80, iframe_url);
var headers = request.headers;
headers.host = iframe_url;
var remoteRequest = httpClient.request(request.method, request.url, headers);
request.on('data', function(chunk) {
remoteRequest.write(chunk);
});
request.on('end', function() {
remoteRequest.end();
});
remoteRequest.on('response', function (remoteResponse){
var body_regexp = new RegExp("<head>"); // regex to find first head tag
var href_regexp = new RegExp('\<a href="(.*)"', 'g'); // regex to find hrefs
response.writeHead(remoteResponse.statusCode, remoteResponse.headers);
remoteResponse.on('data', function (chunk) {
var body = doDecompress(new compress.GunzipStream(), chunk);
body = body.replace(body_regexp, "<head><base href=\"http://"+ iframe_url +"/\">");
body = body.replace(href_regexp, '<a href="#" onclick="javascript:return false;"');
response.write(body, 'binary');
});
remoteResponse.on('end', function() {
response.end();
});
});
}
};
在 var 正文部分,我想阅读正文,例如在这种情况下,通过用 # 替换它们来删除所有 href。这里的问题当然是当我们有一个 gzip 编码/压缩的站点时,它全是乱码,我们无法应用正则表达式。
现在我已经厌倦了摆弄 node-compress 模块:
doDecompress(new compress.GunzipStream(), chunk);
指的是
function doDecompress(decompressor, input) {
var d1 = input.substr(0, 25);
var d2 = input.substr(25);
sys.puts('Making decompression requests...');
var output = '';
decompressor.setInputEncoding('binary');
decompressor.setEncoding('utf8');
decompressor.addListener('data', function(data) {
output += data;
}).addListener('error', function(err) {
throw err;
}).addListener('end', function() {
sys.puts('Decompressed length: ' + output.length);
sys.puts('Raw data: ' + output);
});
decompressor.write(d1);
decompressor.write(d2);
decompressor.close();
sys.puts('Requests done.');
}
但是由于 block 输入是一个对象,所以它失败了,所以我尝试将它作为 chunk.toString() 提供,它也因输入数据无效而失败。
我想知道我是否正朝着正确的方向前进?
最佳答案
解压缩器需要二进制编码的输入。您的响应收到的 block 是 Buffer 的一个实例toString()
方法默认返回一个 UTF-8 编码的字符串。
所以你必须使用 chunk.toString('binary')
让它工作,这也可以在 demo 中看到.
关于proxy - Node.js代理,处理gzip解压,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4594654/
我是一名优秀的程序员,十分优秀!