Kwang Kwang - 1 year ago 89
Node.js Question setting for expressjs

I just tried to use ''
For initial setting, document says the code below

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


and this is my original code.

var app = require('express')();

what's the difference between two?
Specifically 2 questions.

  1. require('http').Server(app) => Why do I need to put app as a argument of Server?

  2. why do i have to use server.listen() instead of app.listen() ??

I looked up the document of node.js and express.js but can't understand...

I'll be really appreciated for your full explanation...

Answer Source

Your original code is using Express to create the HTTP server for you. The reason you can do app.listen() is because it is also returning the server instance so it's essentially a convenience method for:

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

The initial setting in your example is shorthand for:

var http = require('http');
var server = http.createServer();
var express = require('express');
var app = express();
var socketio = require(''); 
server.on('request', app);
var io = socketio(server); 


In this example you are creating a new connection server for web sockets and integrating it into the http server yourself. The reason you are passing app as an argument of Server is so that the express app takes precedence over the socket server for typical http requests.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download