简体   繁体   English

nodejs node-http-proxy设置缓存

[英]nodejs node-http-proxy setup with cache

I'm trying to setup node-http-proxy module with caching node-http-proxy module . 我正在尝试使用缓存node-http-proxy模块设置node-http-proxy模块 I've managed to configure node-http-proxy to do what I need to do in terms of proxying calls, but I would like to find a way to cache some of these calls. 我已经设法配置node-http-proxy来完成我在代理调用方面需要做的事情,但我想找到一种方法来缓存其中一些调用。

My current code is as follows (omitted some config bootstrapping): 我当前的代码如下(省略一些配置bootstrapping):

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

Inside the handler function, I would like to be able to somehow capture what the proxy is reading from "target" and stream it into a fs.createWriteStream('/somepath') before piping it out to res. 在处理程序函数内部,我希望能够以某种方式捕获代理从“目标”读取的内容并将其流式传输到fs.createWriteStream('/ somepath'),然后再将其传递给res。 Then I would modify my function to do look to something along the line: 然后我会修改我的函数来查看沿线的内容:

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

Does anyone know how to do this ? 有谁知道如何做到这一点 ?

The answer to the question ended up being very simple: 这个问题的答案最终非常简单:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM