3

我正在尝试使用 node.js 创建一个 http 缓存代理服务器,在那里我可以转发到任何网页并将它们缓存在我的本地磁盘上!

以下是我的第一次尝试代码:

var http = require('http'),
url  = require('url'),
sys  = require('url');

var fs = require('fs');

var port = "9010";

// function notFound
function notFound(response){
response.writeHead(404, "text/plain");
response.end("404 : File not Found");
}


//create simple http server with browser requet and browser response
http.createServer(function(b_request, b_response){

//Parse the browser request'url
var b_url = url.parse(b_request.url, true);
if(!b_url.query || !b_url.query.url) return notFound(b_response);

//Read and parse url parameter (/?url=p_url)
var p_url = url.parse(b_url.query.url);

//Initialize Http client
var p_client = http.createClient(p_url.port || 80, p_url.hostname);

//Send request
var p_request = p_client.request('GET', p_url.pathname || "/", {
   host: p_url.hostname
});
p_request.end();

//Listen for response
p_request.addListener('response', function(p_response){
    //Pass through headers
    b_response.writeHead(p_response.statusCode, p_response.headers);
    //Pass through data
     p_response.addListener('data', function(chunk){
            b_response.write(chunk);
    });

    //End request
    p_response.addListener('end', function(){
        b_response.end();
    });
});
}).listen(port);

console.log("Server running at http://127.0.0.1:" +port + "/");

我想为我的应用程序使用任何缓存库,例如:Node-static(https://github.com/cloudhead/node-static)、静态缓存、....

如果我访问的网站运行良好,我的应用程序将转发给它。如果不是,我的应用程序将获取并返回缓存在我的磁盘上的数据。

有什么解决方案可以解决这个问题吗?

感谢 !

4

0 回答 0