我目前正在使用代理服务器,在这种情况下,我们必须修改我们通过它推送的数据(通过使用正则表达式)。
在大多数情况下,它工作正常,除了使用 gzip 作为内容编码的网站(我认为),我遇到了一个名为compress的模块并尝试推送我通过解压缩/gunzip 流接收到的块,但它不是真的如我所料。(代码见下文)
我想我会发布一些代码来支持我的问题,这是加载了 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.');
}
但是它失败了,因为块输入是一个对象,所以我尝试将它作为一个 chunk.toString() 提供,它也因输入数据无效而失败。
我想知道我是否朝着正确的方向前进?