Understanding vhost in Express Node.js

I am trying to understand how vhostExpress JS works. Here's a sample working code (forgot where I got it from):

// -- inside index.js --
var EXPRESS = require('express');
var app = EXPRESS.createServer();

app.use(EXPRESS.vhost('dev.example.com', require('./dev').app));

app.listen(8080);


// -- inside dev.js --
var EXPRESS = require('express');
var app = exports.app = EXPRESS.createServer();

app.get('/', function(req, res)
{
    // Handle request...
});

Now, my question is: why do we call createServer()twice? Why does it even work? Is an vhostinternally “merging” of two servers together?

+5
source share
1 answer

Node.js is event driven, and when a request arrives, an event requestis created on http.Server. Thus, basically express.vhost(or indeed, connect.vhost) is an intermediate function that raises an event requestin another instance http.Server:

function vhost(req, res, next){
    if (!req.headers.host) return next();
    var host = req.headers.host.split(':')[0];
    if (req.subdomains = regexp.exec(host)) {
      req.subdomains = req.subdomains[0].split('.').slice(0, -1);
      server.emit('request', req, res);
    } else {
      next();
    }
  };
+10
source

All Articles