以Express应用程序作为参数评估require("http").Server()时会发生什么情况? [英] What is happening when require("http").Server() is evaluated with an Express app as its argument?

查看:146
本文介绍了以Express应用程序作为参数评估require("http").Server()时会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里阅读Socket.io聊天演示: http://socket.io/get-开始/聊天/ 当查看他们的require语句时,我感到困惑.

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');
});

我是正确的,认为require("express")会生成可执行的Express函数(包含所有必需的函数和字段),并且require("http").Server(app)会创建具有其所有字段和函数的http.Server对象.

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.

如果是这样,我很困惑,因为Express会在我们调用.listen函数时创建一个服务器,因此将Express应用程序传递到http模块服务器似乎是多余的,而且是向后的.

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?

推荐答案

http服务器期望具有以下签名的功能:

The http server expects a function which has the following signature:

function(req, res)

require('express')();将创建带有该签名的函数,该函数处理所有表达使路由,中间件等可用的魔术.Express 可以创建其自己的http服务器实例,但是由于还要使用socket.io(它也希望访问http服务器),您将需要一个单独的http实例.

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.

这篇关于以Express应用程序作为参数评估require("http").Server()时会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆