简体   繁体   English

Node.js:require() 和传递变量

[英]Node.js: require() and passing variables

Started a project with npm which created a certain file structure:使用 npm 启动了一个项目,该项目创建了特定的文件结构:

www <-- require() calls app.js; www <-- require() 调用 app.js; instantiates server实例化服务器

app.js <-- instantiates var app = express(); app.js <-- 实例化 var app = express(); and has module.exports = app;并且有 module.exports = app;

Now, I'd like to use sockets.io.现在,我想使用 sockets.io。 In my 'www' file, here is a code snippet:在我的“www”文件中,这是一个代码片段:

var app = require('../app'); ... var server = http.createServer(app);

And I'd like to put all of my server-side socket listeners in app.js, but the following code:我想把我所有的服务器端套接字监听器放在 app.js 中,但是下面的代码:

var io = require('socket.io').listen(server);

requires server as an input.需要服务器作为输入。 How do I make the server I instantiated in 'www' accessible in 'app.js'?如何使我在“www”中实例化的服务器可在“app.js”中访问?

It seems a little strange.好像有点奇怪。 But if you insist on such a structure than you can export an object from www that will have app as it's property and a method that binds socket listeners an receives app object as a param.但是,如果您坚持这样的结构,那么您可以从www导出一个对象,该对象将具有app作为它的属性和一个绑定套接字侦听器并接收app对象作为参数的方法。

module.exports = {
    app:  app,
    bindSocketListeners: function(server, io) {
        io.listen(server);
        return io; 
    } 
};

And call it:并称之为:

var appObj = require('../app');
var io = require('socket.io');
var app = appObj.app;
var server = http.createServer(app);
io  = appObj.bindSocketListeners(server, io) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM