Question

I have found it's easy to use node-http-proxy to route a sub-directory to different ports on a local server. However, I haven't found if there's a way to run a custom function when doing the routing. What I want to do is:

  1. If the service on the target port is not running, start it up, then finish the route
  2. If the service is already running on the target port, just do the route

I'm not asking about how to check for the service and start it, just how to have a function called each time a re-route is going to take place.

Can I do something like this?

var options = {
    route: {
        '/task1' : customFunc('3000'),
        '/task2' : customFunc('3001'),
    }
}

httpProxy.createServer(options).listen(80);
Was it helpful?

Solution

You cannot assign a function as the path value, as that value is parsed as a URL. See here.

Instead, what you can do is intercept the requests before it hits the router, start your services as needed, and then forward the request back to the router:

var init = function(req, res, next){
    if(req.url.indexOf('task1') > -1 && !serviceIsRunning()){
        startService();
        next(); // forward req back to router
    } else {
        // no need to do anything, move request along
        next();
    }    
}

httpProxy.createServer('localhost', options, init).listen(80);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top