Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 429
Tomasz Rakowski Avatar asked Sep 15 '14 19:09

Tomasz Rakowski


1 Answers

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'});         
        }
    });
};
like image 82
Tomasz Rakowski Avatar answered Sep 18 '22 00:09

Tomasz Rakowski