nodejs node-http-proxy设置缓存

时间:2014-09-15 19:35:38

标签: node.js caching proxy

我尝试使用缓存设置node-http-proxy模块 node-http-proxy module。我设法配置node-http-proxy以完成我在代理调用方面需要做的事情,但我想找到一种方法来缓存其中一些调用。

我当前的代码如下(省略了一些配置引导):

var http = require('http');
var https = require('https');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
var fs = require('fs');

var handler = function(req, res) {
    proxy.web(req, res, {target: 'http://localhost:9000'});
};

var server = http.createServer(handler).listen(config.children.http.port, function() {
    console.log('Listening on port %d', server.address().port);
});

var secure = https.createServer(config.children.https.options, handler).listen(config.children.https.port, function() {
    console.log('Listening on port %d', secure.address().port);
});

在处理程序函数中,我希望能够以某种方式捕获代理正在读取的内容" target"并在将它输出到res之前将其流式传输到fs.createWriteStream(' / somepath')。然后我会修改我的函数来做一些事情:

var handler = function(req, res) {
    var path = '/somepath';
    fs.exists(path, function(exists) {
        if(exists) {
            console.log('is file');
            fs.createReadStream(path).pipe(res);
        } else {
            console.log('proxying');
            // Here I need to find a way to write into path
            proxy.web(req, res, {target: 'http://localhost:9000'});
        }
    });
};

有谁知道怎么做?

1 个答案:

答案 0 :(得分:5)

问题的答案最终非常简单:

var handler = function(req, res, next) {

    var path = '/tmp/file';
    fs.exists(path, function(exists) {
        if(exists) {
            fs.createReadStream(path).pipe(res);
        } else {
            proxy.on('proxyRes', function(proxyRes, req, res) {
                proxyRes.pipe(fs.createWriteStream(path));
            });
            proxy.web(req, res, {target: 'http://localhost:9000'});         
        }
    });
};