我目前正在使用 Node.JS 创建一个应用程序,该应用程序利用了 Express 和 Socket.io。随着时间的推移,处理一个文件变得越来越困难,我正在将某些我知道如何做的事情移出,但想知道实现这一目标的最佳方法。
我有一个私有(private)区域构造器类似于:
privateArea.js
function privateArea(props) {
this.id = props.id;
this.name = props.name;
this.users = [];
}
privateArea.prototype.addUser = function(socketId) {
this.users.push(socketId);
};
module.exports = privateArea;
我想让它也可以访问 socket.io
变量,该变量已设置为在单独的 sockets.js
文件中使用,该文件可以通过主要的 app.js
和 express.js
所以我想要这样的结构:
project
| app.js - joins it all together
| express.js - initialises and manages all express routing
| privateArea.js - constructor for private areas - must be able to reference socket.io
| sockets.js - initialises and manages all socket.io sockets and events
任何帮助/示例将不胜感激。
谢谢
最佳答案
我在我的项目中经常使用 socket.io 和 express,并且我开发了一个使事情变得简单的模板。我喜欢进行故障转移,以防套接字连接由于某种原因断开,或者无法建立套接字连接。所以我创建了 http channel 和套接字 channel 。这是一个基本的模块模板:
module.exports = function () {
var exported = {};
var someFunction = function (done) {
//.. code here..//
if (typeof done === "function") {
done(null, true);
}
};
// export the function
exported.someFunction = someFunction;
var apicalls = function (app) {
app.get("/module/someFunction", function (req, res) {
res.header("Content-Type", "application/json");
someFunction(function (err, response) {
if (err) return res.send(JSON.stringify(err));
res.send(JSON.stringify(response));
});
});
};
exported.apicalls = apicalls;
var socketcalls = function (io) {
io.on("connection", function (socket) {
socket.on('module-someFunction', function () {
someFunction(function (err, response) {
if (err) return socket.emit('module-someFunction', err);
socket.emit('module-someFunction', response);
});
});
});
};
exported.socketcalls = socketcalls;
return exported;
}
所以要使用它,我首先需要像这样在我的 app.js 文件中包含该模块:
var mymod = require('./myModule.js');
然后我可以像这样通过 HTTP 和 websocket 启用对该服务的访问:
mymod.apicalls(app); // passing express to the module
mymod.socketcalls(io); // passing socket.io to the module
最后,从前端,我可以检查我是否有套接字连接,如果有,我使用套接字发出“module-someFunction”。如果我没有套接字连接,前端将执行 AJAX 调用而不是“/module/someFunction”,这将在服务器端调用与我使用套接字连接时相同的函数。
作为额外的好处,如果我需要在服务器中使用该函数,我也可以这样做,因为该函数是导出的。看起来像这样:
mymod.someFunction(function (err, response) {
// ... handle result here ... //
});
关于javascript - 模块化 node.js/socket.io/express 应用程序的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25046736/