I was reading the Socket.io Chat Demo here: http://socket.io/get-started/chat/ and I got confused when looking at their require statements.
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');
});
Am I correct in thinking that require("express")
produces an executable Express function (with all of the necessary functions and fields that go with that), and that require("http").Server(app)
creates a http.Server object with all of its fields and functions.
If so, I am confused because Express creates a server when we call the .listen function so it seems redundant and backwards to pass an Express app to an http module server.
So, my question is, what is really happening here?
The http server expects a function which has the following signature:
function(req, res)
require('express')();
will create a function with that signature which handles all the magic that express makes available like routing, middleware, etc. Express can create it's own http server instance, but since you're also using socket.io (which expects access to the http server as well), you'll need a separate http instance.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句