简体   繁体   中英

nodejs node-http-proxy setup with cache

I'm trying to setup node-http-proxy module with caching node-http-proxy module . 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.

My current code is as follows (omitted some config 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. 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'});         
        }
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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