1.0.4 • Published 3 years ago

node-distributor v1.0.4

Weekly downloads
14
License
MIT
Repository
github
Last release
3 years ago

node-distributor

node-distributor is a simple tool to gather requests in one place and redirect them to various other servers using express.

Installation

Using npm:

$ npm i -g npm
$ npm i node-distributor

Usage in Node.js

Create a simple server, that accepts requests on http://server.com:5000/api and redirects them to server2 or server3 on the rest of the url path. A request to http://server.com:5000/api/route1 will be redirected to server2.

var NodeDistributor = require('node-distributor');

/* NOTE:    - errors will always be printed
            - pathPrefix, ssl, key and cert are not required*/
var opts = {
    port: 5000,         // port to listen on; default: 5000
    verbose: false,     // print some infos and warnings; default: false
    pathPrefix: '/api', // default: '/api'
    ssl: false,         // tell ND explicitly to use key and cert; defaul: false
    key: '',            // path to key file
    cert: ''            // path to certificate file
 };

var nd = new NodeDistributor(opts);

var routes = [
    {
        urlPath: '/route1',                 // don't forget the leading slash
        host: 'https://server2.com:1234'    // format: 'address:port'
    },
    {
        urlPath: '/route2',
        host: 'http://server3.com:1234'
    }
];
var app = nd.createListener(routes);
var server = nd.createServer(app);

In order to use middleware functions before or after redirecting requests:

var before = [
    funtion(req, res, next) {
        console.log('request received');
        next();
    }
];

var after = [
    function(req, res, next) {
        console.log('the route was not found');
        next();
    }
];

var app = nd.createListener(routes, before, after);

node-distributor will respond with HTTP 404 by itself, if a route is not found. The function declared in before will be executed before the request is redirected and the function declared in after will executed after a the request was returned (due to an error, so no response was sent).