【问题标题】:nodejs node-http-proxy setup with cache带缓存的 nodejs node-http-proxy 设置
【发布时间】:2014-11-09 10:15:11
【问题描述】:

我正在尝试使用缓存设置 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);
});

在处理函数内部,我希望能够以某种方式捕获代理从“目标”读取的内容,并将其流式传输到 fs.createWriteStream('/somepath') 中,然后再将其传输到 res。然后我会修改我的函数来做一些事情:

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'});
        }
    });
};

有人知道怎么做吗?

【问题讨论】:

    标签: node.js caching proxy


    【解决方案1】:

    这个问题的答案很简单:

    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'});         
            }
        });
    };
    

    【讨论】:

    • 正是我需要的!我为每个请求设置了唯一的路径,它似乎正在工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    相关资源
    最近更新 更多