I am trying to understand how vhost actually works in Express JS. Here’s a working code sample (forgot where I pulled this 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 this even work? Is vhost internally “merging” the two servers together?
Node.js is event-driven, and when a request comes in, the
requestevent is raised on ahttp.Server. So basically,express.vhost(or really,connect.vhost) is a middleware function which raises therequestevent on another instance of ahttp.Server: