【发布时间】:2017-08-31 03:12:18
【问题描述】:
我有点困惑,关于如何在 Node.js 中 require 和使用模块。
我的情况如下:
我在一个文件中编写了一个完整的服务器,它使用 Socket.io 进行实时通信。
现在 index.js 变得相当大了,我想将代码分成几个模块以使其更易于管理。
例如,我有一些功能可以向客户提供调查并获取他们的答案。我将所有这些函数放在一个单独的模块中,并在 index.js 中要求它。到目前为止工作正常。
我唯一关心的是,是否有另一种方法可以在模块内使用 SAME 套接字实例。
我当前的编码如下所示:
index.js:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var Survey = require('./survey');
io.on('connection', function (client) {
client.on('getCurrentQuestion', function (data) {
Survey.getCurrentQuestion(parseInt(data.survey_id), client.id);
});
});
server.listen(port, server_url, function () {
Survey.init(io);
});
survey.js:
var io = null;
var Survey = {};
Survey.init = function(socketio) {
io = socketio;
};
Survey.getCurrentQuestion = function(survey_id, socket_id) {
var response = {
status: "unknown",
survey_id: survey_id
};
// [...] some code that processes everything
// then uses Socket.io to push something back to the client
io.sockets.in(socket_id).emit('getCurrentQuestion', response);
};
module.exports = Survey;
这样可以正常工作,但我不乐意将 init 函数中的 io 传递给所需的模块。
这样做的“正确方法”是什么?
如果我在调查模块中require('socket.io'),它是否与index.js中的实例相同?
我什至如何要求它,因为它需要server,它需要app,它是在index.js 中创建的?
我很困惑,希望有人可以帮助我。谢谢!
【问题讨论】:
标签: javascript node.js sockets module socket.io