What happens when required ("http"). Is server () evaluated using an Express application as an argument?

I read the demo version of Socket.io Chat here: http://socket.io/get-started/chat/ and I was confused looking at their statements of necessity.

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendfile('index.html');
});

io.on('connection', function(socket){
console.log('a user connected');
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

I correctly understood that it require("express")creates an executable Express function (with all the necessary functions and fields that come with it), and that it require("http").Server(app)creates an http.Server object with all its fields and functions.

If so, I got confused because Express creates the server when we call the .listen function, so it seems redundant and back to pass the Express application to the http module server.

So my question is: what is really going on here?

+4
2

HTTP- , :

function(req, res)

require('express')(); , , , , , .. Express http-, socket.io( HTTP-), HTTP-.

+2
var app = require('express')(); //infact, app is a requestListener function. 

var http = require('http').Server(app); // infact, function Server eqs http.createServer;

// infact,app.listen eqs http.listen 

nodejs -

, require ( "express" )() return app - .

//express/lib/express.js   https://github.com/strongloop/express/blob/master/lib/express.js

var proto = require('./application');

exports = module.exports = createApplication;

function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };

  mixin(app, EventEmitter.prototype, false);
  mixin(app, proto, false);

  app.request = { __proto__: req, app: app };
  app.response = { __proto__: res, app: app };
  app.init();
  return app;
}

, node.createServer eqs Server

//nodejs/lib/http.js  https://github.com/nodejs/node/blob/master/lib/http.js

exports.createServer = function(requestListener) {
  return new Server(requestListener);
};

, app.listen eqs http.listen

//express/lib/application.js  https://github.com/strongloop/express/blob/master/lib/application.js

app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};





//nodejs/lib/_http_server.js  https://github.com/nodejs/node/blob/master/lib/_http_server.js

function Server(requestListener) {
  if (!(this instanceof Server)) return new Server(requestListener);
  net.Server.call(this, { allowHalfOpen: true });

  if (requestListener) {
    this.addListener('request', requestListener);
  }

  this.httpAllowHalfOpen = false;

  this.addListener('connection', connectionListener);

  this.addListener('clientError', function(err, conn) {
    conn.destroy(err);
  });
+1

All Articles